各种comprehension

1 什么是comprehension

list、set、dict、generator等本质上是集合。所以,数学上的集合的表示引入到python中,{x| x属于某个集合}。

所以,comprehension本质上是用来表示集合。

2 comprehension的共同特征

最前面的表达式是集合中的元素,后面的是变量的取值范围。它们二者共同决定了这个集合。

3 各个comprehension的不同点

书写方式不同而已。

4 各种comprehension

4.1 list comprehension

中括号[]

4.2 dict comprehension

大括号{}

4.3 set comprehension

大括号{}

4.4 generator comprehension

generator comprehension也是一个generator。

圆括号()

5 通用格式

前括号 x for x in 集合 if 条件 后括号

前括号 x:y for x in 集合1 for y in 集合2 if 条件 后括号

原文地址:https://www.cnblogs.com/hustdc/p/7576020.html