Python学习笔记:列表、字典与集合解析(List, Dict and Set Comprehensions)
1、列表解析
最受喜爱的Python语言特性。过滤一个集合的元素生成一个新的列表。
一般形式:[expr for val in collection if condition]
等价形式:
result = []
for val in collection:
if condition:
result.append(expr)
任务:过滤掉列表里字符串长度不超过3的元素,并将元素转换成大写字母。
方法一、利用列表解析式
方法二、利用for循环生成
2、字典解析
一般形式:dict_comp = {key-expr : value-expr for value in collection if condition}
任务:将单词列表中长度超过3的单词大写找出来,并给出其位置,构成字典。
<