📌  相关文章
📜  python程序检查指定值是否包含在一组值中 - Python(1)

📅  最后修改于: 2023-12-03 15:04:41.262000             🧑  作者: Mango

Python程序检查指定值是否包含在一组值中

在Python中,我们可以使用in关键字来检查指定的值是否包含在一组值中,这组值可以是列表、元组、集合或字典的键。

检查值是否存在于列表中

对于一个普通的列表,我们可以使用in关键字来判断指定的元素是否在列表中。

my_list = [1, 2, 3, 4, 5]
if 3 in my_list:
    print("3 is in the list!")
else:
    print("3 is not in the list.")

输出结果如下:

3 is in the list!

可以看出,当3在列表my_list中时,程序会输出“3 is in the list!”,否则会输出“3 is not in the list.”。

检查值是否存在于元组中

与列表类似,我们也可以使用in关键字来判断指定的元素是否在一个元组中。

my_tuple = (1, 2, 3, 4, 5)
if 3 in my_tuple:
    print("3 is in the tuple!")
else:
    print("3 is not in the tuple.")

输出结果如下:

3 is in the tuple!
检查值是否存在于集合中

与列表和元组不同的是,集合中不允许存在重复的元素,因此可以用来快速地判断指定的元素是否存在于集合中。

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!
检查值是否存在于字典中

对于字典,我们可以检查指定的键是否存在于字典中,而不是检查值。

my_dict = {'name': 'Tom', 'age': 20, 'gender': 'male'}
if 'age' in my_dict:
    print("Age is a key in the dictionary!")
else:
    print("Age is not a key in the dictionary.")

输出结果如下:

Age is a key in the dictionary!
总结

在Python中,我们可以使用in关键字来快速地判断一个值是否存在于一组值中,无论这组值是列表、元组、集合还是字典的键。这种方法很简单、高效,同时也为我们提供了更多的操作空间。