python

python set如何判断元素是否存在

小樊
97
2024-11-22 04:11:50
栏目: 编程语言

可以使用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

0
看了该问题的人还看了