导航

3.python容器推导公式

Posted on 2025-01-28 14:12  小熊_努力学习版  阅读(15)  评论(0)    收藏  举报

1. 列表list
list_1 = [L(x) for x in iterator]# L(x)为列表中迭代生成的元素,x为迭代元素,iteration为迭代器(x从迭代器中提取)
2. 元组tuple
generator = (t(x) for x in iterator)# 注意采用小括号生成的迭代序列为一个生成器
tuple_1 = tuple(generator)
3. 集合set
{}
4. 字典dict
字典的推导公式在for...in 循环时,需要循环键,对应的值通过键进行计算
dict = {key:f(key) for key in iterator}

点击查看代码
# 对python容器的推导公式学习以及python中for循环的理解
# 1. 列表推导式
list_1 = [x*2+1 for x in range(5)]
# 2. 元组推导式
generator_1 = (x*x+2 for x in  range(5))
for i in generator_1:
    print(i)
# 3. 集合推导式
set = {x*2+3 for x in range(5)}
for i in set:
    print(i)
# 4. 字典推导式
dict = {key:key*2+4 for key in range(5)}
for i, j in dict.items(): # 将字典items的key和value的值分别赋给i,j
    print(i,j)