# python学习笔记——推导式创建序列

1212-王同学

,

## 列表推导式

a = [x * 2 for x in range(1, 5)]
# 相当于传统方法：
for x in range(1, 5):
a.append(x*2)
print(a)
# 其他几种举例
b = [x * 2 for x in range(1, 20) if x % 5 == 0]
c = [a for a in 'abcdefg']
print(a)
print(b)
print(c)
# 还可以使用两个循环
cells = [(row, col) for row in range(1, 10) for col in range(1, 10)]
print(cells)
[2, 4, 6, 8]
[10, 20, 30]
['a', 'b', 'c', 'd', 'e', 'f', 'g']
[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6), (2, 7), (2, 8), (2, 9), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (3, 6), (3, 7), (3, 8), (3, 9), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (4, 6), (4, 7), (4, 8), (4, 9), (5, 1), (5, 2), (5, 3), (5, 4), (5, 5), (5, 6), (5, 7), (5, 8), (5, 9), (6, 1), (6, 2), (6, 3), (6, 4), (6, 5), (6, 6), (6, 7), (6, 8), (6, 9), (7, 1), (7, 2), (7, 3), (7, 4), (7, 5), (7, 6), (7, 7), (7, 8), (7, 9), (8, 1), (8, 2), (8, 3), (8, 4), (8, 5), (8, 6), (8, 7), (8, 8), (8, 9), (9, 1), (9, 2), (9, 3), (9, 4), (9, 5), (9, 6), (9, 7), (9, 8), (9, 9)]


## 字典推导式

cc = "two big eyes, a small mouth, a handsome nose"
char_count = {c:cc.count(c) for c in cc}
print(char_count)
{'t': 2, 'w': 1, 'o': 4, ' ': 8, 'b': 1, 'i': 1, 'g': 1, 'e': 4, 'y': 1, 's': 4, ',': 2, 'a': 4, 'm': 3, 'l': 2, 'u': 1, 'h': 2, 'n': 2, 'd': 1}


## 集合推导式

{表达式 for item in 可迭代对象 if 条件判断}

b = {x for x in range(1, 100) if x % 9 == 0}
print(b)
{99, 36, 72, 9, 45, 81, 18, 54, 90, 27, 63}

## 生成器推导式（生成元组）

gnt = (x for x in range(1,100) if x%9==0)
print(tuple(gnt))
print(tuple(gnt))
(9, 18, 27, 36, 45, 54, 63, 72, 81, 90, 99)
()

gnt = (x for x in range(1,100) if x%9==0)
for x in gnt:  # gnt是生成器对象，生成器一个可迭代的对象
print(x, end=",")
print(tuple(gnt))

9,18,27,36,45,54,63,72,81,90,99,()

Vieu3.3主题

Q Q 登 录