(100 days, 2 hours, second day) list comprehension

1. List comprehensions provide a simple way to create lists from sequences. Usually the application program applies some operations to each element of a certain sequence, and uses the result obtained as the element to generate a new list, or creates a sub-sequence according to certain judgment conditions.

Every list comprehension is followed by an expression.

v=[2,4,6]
print([3*x for x in v])
print([[x,x*3] for x in v])
print([3*x for x in v if x>3])
print([3*x for x in v if x<2])
freshfruit = ['  banana', '  loganberry ', 'passion fruit  ']
print([weapon.strip() for weapon in freshfruit])

  

freshfruit = ['banana', 'loganberry ', 'passion fruit']
print(freshfruit)#这一行的作用和下一行一样
print([x.strip() for x in freshfruit]) #随便定义的,strip()函数是把列表中的输出来

  

2. There can be zero to more for or if clauses. The return result is a list generated from the following for and if contexts based on the expression. If you want the expression to deduce a tuple, you must use parentheses.

v1=[2,4,6]
v2=[4,3,-9]
print([x*y for x in v1 for y in v2])  #x和y分别相乘,不是对应位置相乘
print([x+y for x in v1 for y in v2])  #x和y分别相加,不是对应位置相加
print([v1[i]*v2[i] for i in range(len(v2))]) #指定下标就是对应位置相乘

  

3. List comprehensions can use complex expressions or nested functions:

print([str(round(355/113,i)) for i in range(1,6)])

  

 The round() method returns the decimal point of x rounded to n digits.

Guess you like

Origin blog.csdn.net/zhangxue1232/article/details/109320013