温馨提示×

python中set怎样进行元素查找

小樊
81
2024-12-09 23:55:24
栏目: 编程语言

在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

另外,还可以使用集合的__contains__()方法来检查元素是否存在于集合中,例如:

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

0