四、数据类型_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}
上一篇:Java 锁机制了解一下


下一篇:Python笔记1