问题:您需要了解如何在 Python 中使用 “in ”操作符来完成各种任务,如检查集合中是否存在元素、遍历序列或验证字典中是否存在键。

这个运算符是搜索、过滤或有条件地处理序列和集合中元素等任务的基础。

解决方案:

  1. 检查成员: 要检查列表、元组或字符串中是否存在元素,可使用 in 操作符。它会返回一个布尔值(真或假)。
my_list = [1, 2, 3, 4, 5]
if 3 in my_list:
    print ("3 is in the list")

使用 in 操作符 2. 检查字典中的键: 使用 in 操作符验证字典中是否存在键。

my_dict = {"apple": 3, "banana": 5, "cherry": 2}
if "banana" in my_dict:
    print ("The key 'banana' is in the dictionary")

使用 in 操作符 3. 遍历序列: 您可以在 for 循环中使用 in 操作符遍历序列中的元素。

numbers = [1, 2, 3, 4, 5]
for num in numbers:
    print (num)

使用 in 操作符 4. 检查字符串中是否存在子字符串: 要验证字符串中是否存在子串,请使用 in。

sentence = "This is a sample sentence."
if "sample" in sentence:
    print ("The word 'sample' is in the sentence.")

使用 in 操作符

  1. 在条件语句中使用 in: 在条件语句中使用 in 运算符,根据元素的存在作出判断。
my_list = [1, 2, 3, 4, 5]
if 6 not in my_list:
    print("6 is not in the list")

使用 in 操作符