Python常用数据结构-集合——集合推导式
集合推导式
类似列表推导式,同样集合支持集合推导式
语法:{x for x in ... if ...} 使用大括号,最开始放的是提取变量,接下来是for循环语句,最后是循环的判断条件(如果不需要可以省略不写)。
作用:和列表推导式类似,可以用来快速的的可迭代对象中,取出元素,并构建一个新的集合。
例子:寻找hogwartsss 与 hello word 的共相同字母
# 传统for循环方法
set10 = set()
for s in "hogwartsss":
if s in "hello world":
set10.add(s)
print(set10)
# 使用集合推导式
set11 = {s for s in "hogwartsss" if s in "hello world"}
print(set11)
返回