https://qiita.com/ganariya/items/fb3f38c2f4a35d1ee2e8
In order to study Python, I copied a swarm intelligence library called acopy.
In acopy, many interesting Python grammars and idioms are used, and it is summarized that it is convenient among them.
This time, we will learn the if statement of Python list comprehension.
By using the if statement in the list comprehension notation, you can select the value to be used in the list.
For example, if you write a list that identifies even numbers contained in $ [0, N) $
N = int(input())
odds = [x for x in range(N) if x % 2]
print(odds)
You can write as above. It only determines x if the condition ʻif x% 2` is met.
In other words
N = int(input())
arr = []
for x in range(N):
if x % 2 == 0:
arr.append(x)
The above is the equivalent code.
Can be combined with the ternary operator.
Does the condition attached to ** right side ** in list comprehension judge the value? Would you like to? It is ** selection ** of.
The ternary operator, on the other hand, determines the condition from the screened values and changes the value returned for True and False.
It returns an even number as before, but when the ones digit is 0, let's return a list containing $ 0 $ in $ x $.
N = int(input())
'''
[[], 2, 4, 6, 8, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 12, 14, 16, 18, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 22, 24, 26, 28, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
'''
evens = [x if x % 10 else [0] * x for x in range(N) if x % 2 == 0]
print(evens)
The if on the back side after for judges whether it is an even number and sorts it. After passing through the sort, the ternary operator is used to return an array containing $ 0 $ and $ x $ if the ones place is not 0.
To be honest, in the above example, there is no point in using it.
Recommended Posts