How to use list comprehension in python

coldplay.xixi
Release: 2020-08-20 13:24:27
Original
4169 people have browsed it

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 comprehension in python

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)
Copy after login

The output is:

How to use list comprehension in python

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)
Copy after login

The output is:

How to use list comprehension in python

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)
Copy after login

The output is:

How to use list comprehension in pythonFor 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)
Copy after login

The output is:

How to use list comprehension in python

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template