Keep creating , Accelerate growth ! This is my participation 「 Nuggets day new plan · 6 Yuegengwen challenge 」 Of the 28 God , Click to see the event details
[expression for expr1 in sequence1 if condition1
...
for exprN in sequenceN if conditionN]
>>> aList = [x*x for x in range(10)]
# amount to
>>> aList = []
>>> for x in range(10):
aList.append(x*x)
>>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']
>>> aList = [w.strip() for w in freshfruit]
# Equivalent to the following code
>>> aList = []
>>> for item in freshfruit:
aList.append(item.strip())
>>> vec = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> [num for elem in vec for num in elem]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
In this list derivation 2 Cycle , The first one can be regarded as an outer loop , Slow execution ; The second cycle can be regarded as an inner cycle , Fast execution . The execution process of the above code is equivalent to the following writing :
>>> vec = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> result = []
>>> for elem in vec:
for num in elem:
result.append(num)
>>> result
[1, 2, 3, 4, 5, 6, 7, 8, 9]
You can use... In a list derivation if Clause to filter the elements in the list , Only the qualified elements are kept in the result list . The following code can list all the files in the current folder Python Source file :
>>> import os
>>> [filename for filename in os.listdir('.') if filename.endswith(('.py', '.pyw'))]
Select the eligible elements from the list to make a new list :
>>> aList = [-1, -4, 6, 7.5, -2.3, 9, -11]
>>> [i for i in aList if i>0] # All greater than 0 The number of
[6, 7.5, 9]
>>> from random import randint
>>> x = [randint(1, 10) for i in range(20)]
#20 Between [1, 10] The integer of
>>> x
[10, 2, 3, 4, 5, 10, 10, 9, 2, 4, 10, 8, 2, 2, 9, 7, 6, 2, 5, 6]
>>> m = max(x)
>>> [index for index, value in enumerate(x) if value == m]
# All occurrences of the largest integer
[0, 5, 6, 10]
>>> [(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
For list derivations that contain multiple loops , Be sure to know the execution sequence of multiple loops or “ Nested Models ”. for example , The first list derivation above is equivalent to
>>> result = []
>>> for x in [1, 2, 3]:
for y in [3, 1, 4]:
if x != y:
result.append((x,y))
>>> result
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
Ordinary experience I am an o
Un.、Introduction au contrôle d