1. 程式人生 > >python List Comprehensions(列表生成式)

python List Comprehensions(列表生成式)

itl 51cto os模塊 技術分享 tle 出錯 生成式 oos pri

列表生成式: 創建List


一、普通創建List

#!/usr/bin/python

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

技術分享圖片


二、列表生成式

#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, 10) 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類型,其他類型提示出錯

lis6 = [s.lower() for s in L] #lower()是內置函數,將大寫轉為小寫
print lis6;

技術分享圖片


python List Comprehensions(列表生成式)