python List Comprehensions(列表生成式)

列表生成式: 创建List

普通创建List格式:

    1.定义List变量

    2.for .. in ..:

            语句;


列表生成式List格式:

    [ 语句 for .. in ..]


可见,列表生成式只不过是将for里的语句提到for的同行之前而已。        


一、普通创建List

#!/usr/bin/python

#common establish way
lis1 = [];
for x in range(1, 10):
    lis1.append(x);
print "lis1:", lis1;

1.PNG


二、列表生成式

#List comprehensions
lis2 = [x for x in range(1, 10)]
print "lis2:", lis2;

2.PNG


#also can choose the even number in list
lis3 = [x * x for x in range(1, 10) if x%2 == 0]
print "lis3:", lis3;

3.PNG


#two for in list
lis4 = [x + y for x in 'ABC' for y in 'XYZ']
print "lis4:", lis4;

4.PNG


#show the file in directory
import os;     #导入OS模块
lis5 = [d for d in os.listdir('.')]
print lis5;

5.PNG


#convert all big_write string to small_write
L = ['ABC', 'EFG', 'Hij', '8']   #只能为char类型,其他类型提示出错
lis6 = [s.lower() for s in L]   #lower()是内置函数,将大写转为小写
print lis6;

6.PNG


猜你喜欢

转载自blog.51cto.com/13502993/2144598