1 定义
可过滤一个容器的元素,用一种简明的表达式:转换传递过滤的元素,生成新的列表
基本形式:
列表 :list_comp=[expr for val in collection if condition]
集合:set_comp={expr for val in collection if condition}
字典:dict_comp={key-expr:value-expr for val in collection if condition}
(先过滤掉部分元素;再循环获取得到列表、集合、字典等元素;最后经过expr 逻辑处理)
2 常见使用
2.1 列表推导式 list_comp=[expr for val in collection if condition]
常见场景1 :
result = []
for val in collection:
if condition:
result.append(val)
简化如下:给定一个字符串列表,过滤出长度大于2,并且将字母改成大写
strings = ['a', 'as', 'bat', 'car', 'dove', 'python'] [x.upper() for x in strings if len(x) > 2]
2.2 集合推导式 set_comp={expr for val in collection if condition}
每个字段的长度:
unique_lengths = {len(x) for x in strings} unique_lengths
2.3 字典推导式 dict_comp={key-expr:value-expr for val in collection if condition}
set(map(len, strings)) loc_mapping = {val : index for index, val in enumerate(strings)} #枚举 loc_mapping
2.4 嵌套列表推导式
多次循环,顺序排序,放在尾部 常见场景2 : all_data = [['John', 'Emily', 'Michael', 'Mary', 'Steven'], ['Maria', 'Juan', 'Javier', 'Natalia', 'Pilar']] names_of_interest = [] for names in all_data: enough_es = [name for name in names if name.count('e') >= 2] names_of_interest.extend(enough_es) names_of_interest 简化如下: result = [name for names in all_data for name in names if name.count('e') >= 2] result
some_tuples = [(1, 2, 3), (4, 5, 6), (7, 8, 9)] flattened = [x for tup in some_tuples for x in tup] flattened
for循环,从左到右 再到if(
第一步:for tup in some_tuples
第二步:for x in tup;
第三步:再 if过滤 ;
最后再执行相应的逻辑处理)
flattened = []
for tup in some_tuples:
for x in tup:
flattened.append(x)
等同:for tup in some_tuples for x in tup
列表推导式中的列表推导式
[[x for x in tup] for tup in some_tuples]
本篇知识点参考《利用python进行数据分析》,更多知识请阅读原书