Python basic syntax list production

List generation###

List comprehensions, namely List Comprehensions, are very simple but powerful built-in comprehensions in Python that can be used to create lists.

For example, to generate list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] you can use list(range(1, 11)):

list(range(1,11))[1,2,3,4,5,6,7,8,9,10]

But if you want to generate [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
How to do it? One way is to loop, but the loop is too cumbersome, and the list generation can use a line statement instead of loop to generate the above list:

[ x * x for x inrange(1,11)][1,4,9,16,25,36,49,64,81,100]
When writing a list production, put the elements to be generated x*Put x in the front, followed by a for loop, and you can create a list

An if judgment can be added after the for loop, so that we can filter out only even squares:

[ x * x for x inrange(1,11)if x %2==0][4,16,36,64,100]

You can also use a two-level loop to generate a full arrangement:

[ m + n for m in'ABC'for n in'XYZ']['AX','AY','AZ','BX','BY','BZ','CX','CY','CZ']

List generation can also use two variables to generate a list:

d ={'x':'A','y':'B','z':'C',}[k +'='+ v for k, v in d.items()]['y=B','x=A','z=C']

Recommended Posts

Python basic syntax list production
Python basic syntax (1)
Python3 basic syntax
Python basic syntax generator
Basic syntax of Python
Python basic syntax iteration
Python3 list
Python basic syntax and number types
Python basic summary
python list learning
Python basic operators
[902] python list sort
Python basic drawing tutorial (1)
Python function basic learning
Basics of Python syntax
python_ crawler basic learning
Python basic data types
Basic knowledge of Python (1)
Python basic data types
In-depth understanding of python list (LIST)
Python basic knowledge question bank
Python basic drawing tutorial (two)
How does Python list update value
Python introductory notes [basic grammar (on)]
Implementation of reverse traversal of python list
What is list comprehension in python
Python entry notes [basic grammar (below)]
Python file operation basic process analysis
Python crawler basic knowledge points finishing
Real zero basic Python development web