可以使用in關鍵字來判斷一個元素是否存在于set中,例如:
my_set = {1, 2, 3, 4, 5}
if 3 in my_set:
print("3 exists in the set")
else:
print("3 does not exist in the set")
輸出結果為:
3 exists in the set
另外,還可以使用set的.contains()方法來判斷元素是否存在,例如:
my_set = {1, 2, 3, 4, 5}
if my_set.contains(3):
print("3 exists in the set")
else:
print("3 does not exist in the set")
輸出結果同樣為:
3 exists in the set