Make a note of what you thought was important in learning python.
number_list=[]
for number in range(1,6):
number_list.append(number)
You can make a list of numbers from 1 to 5 with this code. However, you can also write like this
number_list=[number for number in range(1,6)]
This one is smarter
You can also add conditional expressions
a_list=[number for number in range(1,6) if number % 2 == 1 ]
You can make an odd list from 1 to 5 with this code Let's compare it with the writing style that does not use comprehension
a_list=[]
for number in range(1,6):
if number % 2 ==1:
a_list.append(number)
The comprehension is much more compact
Multiple loops can also use comprehensions
for i in range(1,4):
for k in range(1,6):
print(i,k)
List comprehension ver
S =[[i,k] for i in range(2,4) for k in range(1,5)]
print(S)
Dictionaries also have comprehensions. There was a comprehensive notation in the book Basically the same writing style as list comprehension.
di={key:key**2 for key in range(1,5)}
You can create a dictionary like this {1: 1, 2: 4, 3: 9, 4: 16}
Tuples have no inclusions
num=(i for i in range(1,4))
You can create a generator object like this. ** I don't know what the generator is now. ** **
Recommended Posts