一、len()函數
判斷List裡面有沒有該值最直觀的方法就是使用Python自帶的len()函數。首先假設我們有一個List called list1,我們需要判斷是否存在值為value1的元素:
list1 = [value1, value2, value3, ...]
if len([i for i in list1 if i == value1]) > 0:
print("Value exists in the List!")
else:
print("Value does not exist in the List!")
上述代碼首先利用List comprehension將List里與value1相等的元素篩選出來,然後通過len()函數得到篩選後的List的長度。如果長度大於0,則說明List裡面存在值為value1的元素。
二、in和not in
Python中還有一種簡單的判斷List中是否含有某個值的方法,就是使用in和not in關鍵字。
list1 = [value1, value2, value3, ...]
if value1 in list1:
print("Value exists in the List!")
else:
print("Value does not exist in the List!")
代碼中的in關鍵字用於判斷value1是否在list1裡面,如果存在,則輸出「Value exists in the List!」,否則輸出「Value does not exist in the List!」。
三、count()函數
List對象也自帶了一個方法count(),用來統計列表中某元素出現的次數。如果對目標值的狀態不關心,只想知道它在List中出現了幾次,這個方法就會十分有用。
list1 = [value1, value2, value3, ...]
count = list1.count(value1)
if count > 0:
print("Value exists in the List!")
else:
print("Value does not exist in the List!")
上述代碼首先對list1中value1出現的次數進行計數,再通過判斷計數值的大小從而判斷value1是否存在於list1中。
四、index()函數
List對象也自帶了一個方法index(),用來獲取某個元素在列表中第一次出現的索引。
index = list1.index(value1) # value1為目標值
if index >=0:
print("Value exists in the List!")
else:
print("Value does not exist in the List!")
如果目標值value1存在於list1中,index()方法將返回目標值第一次出現的下標,否則將拋出異常。
五、lambda表達式
如果想要一行代碼實現判斷List中是否有某個值,可以使用lambda表達式。
list1 = [value1, value2, value3, ...]
is_value_exist = lambda list1, x : True if x in list1 else False
print(is_value_exist(list, value1))
上述代碼中,我們將判斷是否存在目標值的代碼寫成一個lambda表達式,並通過調用lambda表達式的方式得到結果。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/307250.html