Python中的推导式
List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.
1. 列表推导式:能非常简洁的构造一个新列表:只用一条简洁的表达式即可对得到的元素进行转换变形
基本格式:[expr for value in collection if condition]
过滤条件可有可无,取决于实际应用,只留下表达式;相当于下面这段for循环:
result = []
for value in collection:
if condition:
result.append(expr)
例1:过滤掉长度小于3的字符串列表,并将剩下的转换成大写字母
>>> names = ['Bob','Tom','alice','Jerry','Wendy','Smith']
>>> [name.upper() for name in names if len(name)>3]
['ALICE', 'JERRY', 'WENDY', 'SMITH']
例2:求(x,y)其中x是0-5之间的偶数,y是0-5之间的奇数组成的元祖列表
>>> [(x,y) for x in range(5) if x%2==0 for y in range(5) if y %2==1]
[(0, 1), (0, 3), (2, 1), (2, 3), (4, 1), (4, 3)]
2. 字典推导式
基本格式:{ key_expr: value_expr for value in collection if condition }
例:用字典推导式以字符串以及其长度建字典
>>> strings = ['import','is','with','if','file','exception']
>>> D = {key: val for val,key in enumerate(strings)}
>>> D
{'exception': 5, 'is': 1, 'file': 4, 'import': 0, 'with': 2, 'if': 3}
3. 集合推导式
集合推导式跟列表推导式非常相似,唯一区别在于用{}代替[]
基本格式:{ expr for value in collection if condition }
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/30319453/viewspace-2121768/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/30319453/viewspace-2121768/