[PYTHON] Master the inclusion notation

What is a comprehension?

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.

Basic

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)]

Use conditional branching with if

if only

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.

When using if else

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.

When there are multiple subscripts

Pattern to line up

xx = [i+j for i in i_list for j in j_list]

Nested pattern

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.

Pattern using zip

Arrange with (0,0), (1,1), (2,2), ...

xx = [i+j for i,j in zip(mylist_i,mylist_j)]

To avoid plunging into the swamp

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

Master the inclusion notation
This and that of the inclusion notation.
Python basic course (10 inclusion notation)
Master the rich features of IPython
Master the type with Python [Python 3.9 compatible]
Master the weakref module in Python
[Blender x Python] Let's master the material !!
Python Master RTA for the time being
Memorandum of python beginners About inclusion notation