A notation that can be used when creating lists and dictionaries in python. Since python has a slow for loop, using comprehensions when creating lists and dictionaries can make it much faster.
When making a list, it looks like this.
new_list = [f(myiter) for myiter in origin_list]
You can also make a dictionary by replacing [] with {}.
new_dict = {indexes[myiter]:f(myiter) \
for myiter in origin_list}
The basic pattern is as follows.
[(Expression using iterator) for(iterater)in (original iterable object)]
If you use only one if, add ** at the end **.
Extract odd numbers up to 10
odd = [i for i in range(10) if i%2 != 0]
# [1,3,5,7,9]
At this time, if works as a filter.
If you also use else, add ** before ** for.
Odd numbers"odd", Even numbers"even"return it
xx = ["even" if i%2==0 else "odd" for i in range(10)]
# ['even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd']
The reason why the if must be prefixed is that the if at this time is a part of the ternary operator, unlike the previous if.
"even" if i% 2 == 0 else "odd" `` `is one expression, and it will be repeated with for.
~~ You cannot use multiple else. ~~ Elif cannot be used when making multiple conditional branches. This can be achieved by using multiple if else.
xx = [i+j for i in i_list for j in j_list]
xx = [[i+j for i in range(3)] for j in range(5)]
If you want to use numpy operations, pass it to np.array.
xx = np.array([[i+j for i in range(3)] for j in range(5)])
numpy.array is pretty smart, so it can mold double, triple, and quadruple properly.
Arrange with (0,0), (1,1), (2,2), ...
xx = [i+j for i,j in zip(mylist_i,mylist_j)]
You may have come this far and already be "Uh". Since there are no rules for line breaks in list comprehensions, one line becomes long and obfuscated. So if it gets longer, be sure to insert a line break properly **.
In the case of VS Code, if you put \ in the first line, it will be formatted nicely after that. Actually, it runs with or without .
#Absolute line break when using if
xx = ["even" if i % 2 == 0 else "odd" \
for i in range(10)]
#If the expression is long, insert a line break where it is long
zz = [np.sin(xx) + np.random.rand(xx.shape) \
for xx in list_xx]
Recommended Posts