Python uses the list derivation method: 1. It is used to create a new list using other lists; 2. It can transform and filter the original list; 3. Transform and filter multiple nested lists.
How to use list comprehensions in python:
List comprehensions in python are used to create a list using other lists New list.
The basic form is: [Expression for variable in list]
For example:
# 想得到1-10的平方组成的list list_1_10 = [x**2 for x in range(1,11)] print(list_1_10)
The output is:
A more complex list expression can transform and filter the original list.
For example:
# 想得到1-10中为偶数的平方组成的list example = [i**2 for i in range(1,11) if i%2 == 0 ] print(example)
The output is:
and transform and filter multiple nested lists.
For example:
# 想得到多重嵌套中的数是2的倍数的平方组成的list example2 = [[1,2,3],[4,5,6],[7,8,9],[10]] example3 = [j**2 for i in example2 for j in i if j%2 == 0] print(example3)
The output is:
For example:
# 想得到多重嵌套的list中一重嵌套中list长度大于1的list中的数为2的倍数的平方组成的list example4 = [[1,2,3],[4,5,6],[7,8,9],[10]] exmaple5 = [j**2 for i in example2 if len(i)>1 for j in i if j%2 == 0] print(exmaple5)
The output is:
Related learning recommendations:python video tutorial
The above is the detailed content of How to use list comprehension in python. For more information, please follow other related articles on the PHP Chinese website!