三种常见生成式(列表,字典,集合)

列表生成式

生成式语法:[被追加的数据 循环语句 循环或者判断语句]

ls1t  = []
for i in range(10,20)
	lst1.append( i *10)
print(lst1)
**结果**
[100, 110, 120, 130, 140, 150, 160, 170, 180, 190]

lst2 = [i * 10 for i in range(10,20)]
print(lst2)
**结果**
[100, 110, 120, 130, 140, 150, 160, 170, 180, 190]

示例2
#(10到19中偶数)*10放入列表中
lst3 = [i * 10 for i in range(10,20) if i % 2 ==0]
print(lst3)
结果
[100, 120, 140, 160, 180]


示例3

for i in range(1, 5):
    for j in range(1, 5):
        lst4.append(i * j)
 #同上
 lst4 = [i * j for i in range(1,5) for j range(1,5)]
 print(lst4)
 
 **结果**
 [1, 2, 3, 4, 2, 4, 6, 8, 3, 6, 9, 12, 4, 8, 12, 16]

字典生成式

lst5 = [‘张三’,‘李四’,‘王五’]
for i in range(0, len(lst5)):
dict1[i + 1] = lst5[i]

#同上
dict1={i+1:lst5[i] for i range(0,len(lst5)) }
print(dict1)

结果
{1: ‘张三’, 2: ‘李四’, 3: ‘王五’}

集合生成式

for i in range(1, 4):
for j in range(1, 4):
if i == j:
set1.add(i * j)

set1 = {i * j for i in range(1, 4) for j in range(1, 4) if i == j}
print(set1)
结果
{1, 4, 9}

你可能感兴趣的:(python基础)