List generation: Creating a list
Normal Create List format:
1. Defining a list variable
2.for.. In.. :
Statement
List-generated lists format:
[Statement for ...]
As you can see, the list generation is just a matter of referring the for statement to the for peer.
First, the normal creation list
#!/usr/bin/python
#common Establish
Lis1 = [];
For x in range (1, 10):
Lis1.append (x);
Print "Lis1:", lis1;
Ii. List-Generated
#List comprehensions
LIS2 = [x for x in range (1, 10)]
Print "Lis2:", Lis2;
#also can choose the even number in list
LIS3 = [x * x for x in range (1, ten) if x%2 = = 0]
Print "Lis3:", Lis3;
#two for in list
LIS4 = [x + y for x in ' ABC ' for y in ' XYZ ']
Print "LIS4:", LIS4;
#show the file in directory
Import OS; #导入OS模块
LIS5 = [D for D in Os.listdir ('. ')]
Print lis5;
#convert all Big_write string to Small_write
L = [' ABC ', ' EFG ', ' Hij ', ' 8 '] #只能为char类型, other types prompt error
LIS6 = [S.lower () for S in L] #lower () is a built-in function that converts uppercase to lowercase
Print LIS6;
Python list comprehensions (list-generated)