程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Thoroughly understand Python list derivation

編輯:Python

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

List derivation grammar and application cases

  • List derivation ( Also known as list parsing ) Provides a concise way to create lists . Its structure is to include an expression in a square bracket , And then a for sentence , And then there was 0 One or more for perhaps if sentence . That expression can be arbitrary , It means you can put any type of object in the list . The result will be a new list , In this case, with if and for Statement is the expression of the context, which is generated after running .
  • The list derivation is logically equivalent to a circular statement , Just more concise in form . The grammatical form is :
[expression for expr1 in sequence1 if condition1
...
for exprN in sequenceN if conditionN]
  • Execution order of list derivation : The statements are nested , The second sentence on the left is the outermost layer , Go one floor to the right in turn , The first sentence on the left is the last layer .
>>> 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())
  • Use list derivation to tile nested lists .
>>> 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]
  • Use... In list derivation if Filter out elements that don't fit the criteria .

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]
  • Find all the positions of the largest element in the list .
>>> 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]
  • Traverse multiple lists or iteratable objects at the same time in the list derivation .
>>> [(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)]

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved