February 12, 2015 15:38:52Hits: 32624
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 PlainCopy
- >>> 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 PlainCopy
- >>> L= []
- >>> for x in range (1, Ten):
- ... L.append (x*x)
- ...
- >>> L
- [1, 4, 9, (+), +, +, +, Bayi] /c5>
and list generation, you can use a sentence instead of the tedious loop above to complete the above operation:
[Python]View PlainCopy
- >>> Print [x*x for x in range (1, one )]
- [1, 4, 9, +,------------------]
- >>>
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 PlainCopy
- >>> [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 PlainCopy
- >>> Print [M + N for m in ' ABCD ' for N in ' XYZ ']
- [' AX ', ' AY ', ' AZ ', ' BX ', ' by ', ' BZ ', ' CX ', ' CY ', ' CZ ', ' DX ', ' DY ', c19> ' DZ ']
- >>>
How to use two variables to generate a list:
[Python]View PlainCopy
- D = {' Java ': 'a ', ' C ': 'a ', ' + C ' : ' A '
- L = [k +' = ' +v for K, V in d.iteritems ()]
- 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 PlainCopy
- L = [' Java ', ' C ', ' Swift ', ' Python ', 123]
- Print [S.lower () if isinstance (S, str) else s for s in L]
Python Learning nine: list-generated