List derivation : Quickly generate a list of specific requirements in a very concise way
grammar [ expression for Variable in Sequence or iteration object ]
1、 usage 1
# give an example 1
list = [i for i in range(5)]
print(list) #-->[0, 1, 2, 3, 4]
2、 usage 2
# give an example 2: Use list derivation to implement nested lists
nums= [[1,2,3],[4,5,6],[7,8,9]]
list2 = [num for elem in nums for num in elem] # first for It's an external circulation , the second for Internal circulation , Internal loop execution is fast
print(list2) #-->[1, 2, 3, 4, 5, 6, 7, 8, 9]
# It's equivalent to the following
ret = []
for elem in nums:
for num in elem:
ret.append(num)
print(ret)#-->[1, 2, 3, 4, 5, 6, 7, 8, 9]
3、 Use three
# give an example 3: Filter out elements that don't fit the criteria , Reference force buckle 448 topic : Missing numbers
nums = [1,6,8,9,0,4]
list = [i for i in nums if i > 5]# Filter out the array greater than 5 The number of
print(list)#-->[6, 8, 9]
4、 Use four
# give an example 4: Use multiple loops to realize any combination of multiple sequence elements
list = [(x,y) for x in [1,2,3] for y in[2,3,4] if x!=y]
print(list)#-->[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 2), (3, 4)]
5、 usage 5
# give an example 5: Realize matrix transpose , This is a little hard to understand
matrix = [[1,2,3],[4,5,6],[7,8,9]]
re_matrix = [[row[i] for row in matrix] for i in range(3)]
print(re_matrix)#-->[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
# amount to :( Leave it to you to think , Actually, I didn't figure it out )
6、 usage 6
# give an example 6: List derivation supports file object iteration
fp = open("D:\test.txt",'r',encoding = 'utf-8')
print([line for line in fp])
fp.close()
Example :
# subject : Print out 100 Prime number within
# answer
import math
l = [p for p in range(2,100) if 0 not in[p%d for d in range(2,int(math.sqrt(p))+1)]]
print(l)#-->[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
Last :
# One sentence per day
print(" Advise you not to cherish the wisp of gold , Advise you to cherish the youth ")#--》 I advise you not to pay too much attention to fame and wealth , I advise you to cherish your best time in school
Reference resources : That must be a cool blog