温馨提示×

python的set怎样判断成员

小樊
85
2024-11-19 11:17:39
栏目: 编程语言
Python开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Python中,可以使用in关键字来判断一个元素是否在一个集合(set)中。例如:

my_set = {1, 2, 3, 4, 5}

if 3 in my_set:
    print("3 is in the set")
else:
    print("3 is not in the set")

输出结果:

3 is in the set

另外,还可以使用集合的issubset()issuperset()方法来判断一个集合是否是另一个集合的子集或超集。例如:

set_a = {1, 2, 3}
set_b = {1, 2, 3, 4, 5}

if set_a.issubset(set_b):
    print("set_a is a subset of set_b")
else:
    print("set_a is not a subset of set_b")

if set_b.issuperset(set_a):
    print("set_b is a superset of set_a")
else:
    print("set_b is not a superset of set_a")

输出结果:

set_a is a subset of set_b
set_b is a superset of set_a

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:python中set如何判断成员

0