在Python中,可以使用in
關鍵字來判斷一個元素是否存在于列表、元組、集合或字典中。例如:
# 判斷元素是否存在于列表中
my_list = [1, 2, 3, 4, 5]
if 3 in my_list:
print("3 is in the list")
# 判斷元素是否存在于元組中
my_tuple = (1, 2, 3, 4, 5)
if 6 not in my_tuple:
print("6 is not in the tuple")
# 判斷元素是否存在于集合中
my_set = {1, 2, 3, 4, 5}
if 2 in my_set:
print("2 is in the set")
# 判斷鍵是否存在于字典中
my_dict = {'a': 1, 'b': 2, 'c': 3}
if 'd' not in my_dict:
print("'d' is not in the dictionary")
除此之外,還可以使用index()
方法來判斷元素在列表中的索引位置,如果元素不存在,則會拋出ValueError
異常。例如:
my_list = [1, 2, 3, 4, 5]
try:
index = my_list.index(3)
print("3 is at index", index)
except ValueError:
print("3 is not in the list")