Python 列表解析

xiaoxiao2021-02-28  4

列表解析基本语法:

[expr for iter_var in iterable]

这个语句的核心是for循环,它迭代iterable对象的所有条目。列表解析可以有效的替代lambda。

>>> map(lambda x: x**2, range(6)) [0, 1, 4, 9, 16, 25] >>> [x ** 2 for x in range(6)] [0, 1, 4, 9, 16, 25]

使运行效率更高。

结合if语句,

[expr for iter_var in iterable if cond_expr] >>> s = [1, 2, 3, 5, 6, 8, 7, 31, 99] >>> filter(lambda x: x%2, s) [1, 3, 5, 7, 31, 99]

完全可以用列表解析替代

>>> [i for i in s if i%2] [1, 3, 5, 7, 31, 99]

矩阵样例

>>> [(x + 1, y + 1) for x in range(3) for y in range(3)] [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)] >>> [(x, y) for x in range(3) for y in range(3)] [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

磁盘文件样例

f = open('xxx.txt', 'r') len([word for line in f for word in line.split()])#循环遍历所有行和所有单词

计算单词个数

f.seek(0) sum([len(word) for line in f for word in line.split()])

回到文件开头,计算单词所有单词长度。

列表解析实现99乘法表

print('\n'.join([''.join(['%s*%s=%-2s '%(y,x,x*y)for y in range(1,x+1)])for x in range(1,10)]))
转载请注明原文地址: https://www.6miu.com/read-2400062.html

最新回复(0)