其他分享
首页 > 其他分享> > 四、数据类型_6.(3).set - set推导式

四、数据类型_6.(3).set - set推导式

作者:互联网

set推导式

varset = {1,2,3,4,5,6,7}
普通set推导式
newset = {i<<2 for i in varset}
print(newset)

{4, 8, 12, 16, 20, 24, 28}
带有条件判断的set推导式
newset = {i<<2 for i in varset if i % 2 == 0}
print(newset)

{8, 16, 24}
带有循环的set推导式
# (1)
var1 = {1,2,3}
var2 = {7,8,9}
newset = set()
for n in var1 :
    for m in var2 :
        newset.add(n + m)
print(newset)

# (2)
var1 = {1,2,3}
var2 = {7,8,9}

newset = {n + m for n in var1 for m in var2}
print(newset)

{8, 9, 10, 11, 12}
{8, 9, 10, 11, 12}
带有条件判断和循环的set推导式
var1 = {1,2,3,4,5}
var2 = {6,7,8,9,10}
newset = {n+m for n in var1 for m in var2 if n%2==1 and m%2==0}
print(newset)

{7, 9, 11, 13, 15}

标签:11,set,var1,推导,var2,数据类型,newset
来源: https://www.cnblogs.com/HyeJeong/p/15468707.html