搜集一些语法糖
去掉列表中每个元素头尾的空格
>>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']
>>> [str.strip() for str in freshfruit]
['banana', 'loganberry', 'passion fruit']
把列表中,大于3的元素,乘以2
>>> vec = [2, 4, 6]
>>> [2*x for x in vec if x > 3]
[8, 12]
把列表1的每一个元素和列表2的每一个元素相乘
>>> lst1 = [2, 4, 6]
>>> lst2 = [4, 3, -9]
>>> [x*y for x in lst1 for y in lst2]
[8, 6, -18, 16, 12, -36, 24, 18, -54]
获取[0-10)的平方
[x**2 for x in range(10)]
或
map(lambda x : x*x, range(10))
获取[0-10)中奇数的平方
[x**2 for x in filter( lambda x : x%2, range(10) )]