# Python列表推导学习

2017-01-12 10:03:01来源:作者:工学1号馆人点击

1.平方列表

squares = []for x in range(10): squares.append(x**2)

squares = [x**2 for x in range(10)]

2. 整除3的数字列表

numbers = []for x in range(100): if x % 3 == 0: numbers.append(x)

numbers = [x for x in range(100) if x % 3 == 0] 3.找出质数

noprimes = []for i in range(2, 8): for j in range(i*2, 50, i): noprimes.append(j)primes = []for x in range(2, 50): if x not in noprimes: primes.append(x)

noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)]primes = [x for x in range(2, 50) if x not in noprimes]

noprimes = set(j for i in range(2, 8) for j in range(i*2, 50, i))primes = [x for x in range(2, 50) if x not in noprimes] 4.嵌套列表降维

matrix = [[0,1,2,3], [4,5,6,7], [8,9,10,11]]

flattened = []for row in matrix: for i in row: flattened.append(i)

flattened = [i for row in matrix for i in row]

5. 模拟多个掷硬币事件

from random import randomresults = []for x in range(10): results.append(int(round(random())))

from random import randomresults = [int(round(random())) for x in range(10)]

6. 移除句子中的元音字母

sentence = 'Your mother was a hamster'

vowels = 'aeiou'non_list = []for l in sentence: if not l in vowels: non_list.append(l)nonvowels = ''.join(non_list)

vowels = 'aeiou'nonvowels = ''.join([l for l in sentence if not l in vowels])

vowels = 'aeiou'nonvowels = ''.join(l for l in sentence if not l in vowels)

7.获取目录里的文件名列表

import osfiles = []for f in os.listdir('./my_dir'): if f.endswith('.txt'): files.append(f)

import osfiles = [f for f in os.listdir('./my_dir') if f.endswith('.txt')]

import osfiles = [os.path.join('./my_dir', f) for f in os.listdir('./my_dir') if f.endswith('.txt')] 8.将csv文件读取为字典列表

import csvdata = []for x in csv.DictReader(open('file.csv', 'rU')): data.append(x)

import csvdata = [ x for x in csv.DictReader(open('file.csv', 'rU'))]