假設我有這個串列:
common_list = ['Potato', 'Tomato', 'Carrot']
我想檢查是否common_list[3]存在;如果沒有,我想添加一些東西。這是我嘗試過的:
if common_list[2] and not common_list[3]:
common_list.insert(3, 'Lemon')
但它給了我錯誤:
IndexError: list index out of range
uj5u.com熱心網友回復:
這完全取決于您要執行的檢查型別。這里有一些可能性。
檢查是否正好有三個專案:
if len(common_list) == 3:
common_list.append('Lemon')
檢查少于四項:
if len(common_list) < 4:
common_list.append('Lemon')
檢查沒有第四項,或者第四項存在但設定為None:
if len(common_list) < 4 or common_list[4] is None:
common_list.append('Lemon')
檢查串列中是否尚未包含'Lemon':
if 'Lemon' not in common_list:
common_list.append('Lemon')
當您可以通過簡單的if檢查避免它們時,不要觸發和捕獲例外。畫風很差 例外很昂貴,捕獲它們很慢。嘗試僅將它們用于真正特殊的情況,如果確實發生了錯誤,您會感到驚訝。
uj5u.com熱心網友回復:
也許您會嘗試嘗試例外方法?
common_list = ['Potato', 'Tomato', 'Carrot']
try:
common_list[3]
except IndexError:
common_list.insert(3, 'Lemon')
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/311483.html
上一篇:為串列串列中的元素添加引號
