在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