Python中的運算符'in'是一個成員運算符,用于判斷某個元素是否存在于一個序列中。
# 簡單的使用'in'運算符的例子 fruits = ['apple', 'banana', 'orange'] if 'apple' in fruits: print("Yes, 'apple' is in the fruits list.") else: print("No, 'apple' is not in the fruits list.") # 輸出:Yes, 'apple' is in the fruits list.
使用'in'運算符的語句可以在序列中查找元素。如果元素存在,運算符返回True,否則返回False。
# 'in'運算符結合循環可以遍歷序列中的所有元素 marks = [67, 80, 90, 78, 89] for score in marks: if score >= 80: print(score, "is passed.") else: print(score, "is failed.") # 輸出: # 67 is failed. # 80 is passed. # 90 is passed. # 78 is failed. # 89 is passed.
'in'運算符也可以和字符串、集合等類型的對象一起使用,實現相應的成員判斷操作。
# 將字符串視為序列 word = "banana" if 'a' in word: print("Yes, 'a' is in the word.") else: print("No, 'a' is not in the word.") # 輸出:Yes, 'a' is in the word. # 將集合視為一個序列 s = set([2, 4, 6, 8, 10]) if 6 in s: print("Yes, 6 is in the set.") else: print("No, 6 is not in the set.") # 輸出:Yes, 6 is in the set.
總之,運算符'in'在Python中非常常用,是一個非常實用的運算符。可以用于判斷元素是否存在于序列中、遍歷序列等操作。