List generation is a very powerful expression built into Python that generates a list.
If you want to generate a list [1, 2, 3, 4, 5, 6, 7, 8, 9] You can use range (1, 10):
[python] view plain copy print?
- >>> Range (1, 9)
- [1, 2, 3, 4, 5, 6, 7, 8]
But what if you want to build [1*1, 2*2, 3*3, ..., 10*10]? You can use loops:
[python] view plain copy print?
- >>> L= []
- >>> for x in range (1, Ten):
- ... L.append (x*x)
- ...
- >>> L
- [1, 4, 9, +, (+), +, +, Bayi]
and list generation, you can use a sentence instead of the tedious loop above to complete the above operation:
[python] view plain copy print?
- & Gt;>> print [x*x for x in range (1 , 11)]
- [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]  
- >>>   
List-Generated writing format: [x*x for X in range (1, 11)]
First: Put the elements you want to create x*x to the front
Second: Follow the For loop
This allows the list to be created.
The For loop can also be followed by an if judgment, so that even squares can be filtered out:
[python] view plain copy print?
- >>> [x*x for x in range (1, one ) if x2 = = 0]
- [4, +, +,-+ ]
- >>>
Of course, you can use a two-layer loop to generate a full array:
[python] view plain copy print?
- >>> < span class= "keyword" >print [m + n for m in "ABCD" for n in ' XYZ ']
- [' AX ', ' AY ', ' AZ ', ' BX ', ' by ', ' BZ ', ' CX ', ' CY ', ' CZ ', ' DX ', ' DY ', ' DZ ' ']
- >>>
How to use two variables to generate a list:
[python] view plain copy print?
- d = { ' Java ': "the" , ' C ': " , ' C + + ': " } ";
- l = [k+ ' = ' +v for k , V in d.iteritems ()]
- &NBSP;&NBSP;
- print l
Finally, let's do an exercise:
L = [' Java ', ' C ', ' Swift ', ' Python ', 123], now there is a list containing strings, and integers, the list of uppercase characters into lowercase, pushed out to another list ":
1. Use the built-in isinstance function to determine if a variable is a string
2, S.lower () You can convert one uppercase letter to lowercase.
3. Increase the IF statement to ensure that the list generation is executed correctly.
The code is as follows:
[python] view plain copy print?
- L = [' Java ', ' C ', ' Swift ', ' Python ', 123]
- Print [S.lower () if isinstance (S, str) else s for s in L]
Python Learning nine: list-generated