2017-05-05 26 views
0

我有一個通常包含項目但有時爲空的列表。Python - 列表索引超出if語句的範圍

列表中的三項添加到數據庫中,但如果它是空的,則會遇到錯誤,即使我正在使用if語句。

if item_list[0]: 
    one = item_list[0] 
else: 
    one = "Unknown" 

if item_list[1]: 
    two = item_list[1] 
else: 
    two = "Unknown" 

if item_list[2]: 
    three = item_list[2] 
else: 
    three = "Unknown" 

如果列表爲空,則仍然會出現list index out of range錯誤。我找不到任何其他方式可以完成,但必須有更好的方法(我也讀過,你應該避免使用else陳述?)

+1

我很想知道你在哪裏看,你不應該使用'else'語句。你能提供一個來源嗎? –

+0

@AustinHastings沒有單一的來源,只是通過評論這是不好的做法。 – Sen

回答

2

如果列表爲空,則列表中沒有索引;並嘗試訪問列表的索引會導致錯誤。

該錯誤實際上發生在if語句中。

,你可以得到你所期望通過這樣的結果:

one, two, three = item_list + ["unknown"] * (3 - len(item_list)) 

這行代碼創建了一個包含在item_list串聯和列表(3減去item_list大小)「未知的臨時列表「串;這總是一個3項列表。然後,它unpacks此列表中onetwothree變量


細節:

  • 您可以乘列表,以獲得與重複的項目更大的列表:['a', 1, None] * 2['a', 1, None, 'a', 1, None]。這用於創建「未知」字符串的列表。請注意,將列表乘以0會導致一個空列表(如預期的那樣)。
  • 可以使用加法運算符連接2個(或更多)列表:['a', 'b'] + [1, 2]給出['a', 'b', 1, 2]。這用於從item_list和乘法創建的「未知」列表創建3項列表。
  • 您可以unpack列出幾個變量與賦值運算符:a, b = [1, 2]給出a = 1 and b = 2。它甚至可以使用擴展拆包a, *b = [1, 2, 3]給出a = 1 and b = [2, 3]

例如:如果你試圖訪問一個不存在的數組元素

>>> item_list = [42, 77] 
>>> one, two, three = item_list + ["unknown"] * (3 - len(item_list)) 
>>> one, two, three 
(42, 77, 'unknown') 
+0

完美,謝謝!你有沒有資源可以學習內聯/壓縮的風格(即'1,2,3 = item_list + [「unknown」] *(3-len(item_list))'')。我不太清楚你會怎麼稱呼它 – Sen

+0

@Sen:我剛剛添加了關於使用機制的詳細信息,但無法找到每個文檔。我不知道任何資源教學寫緊湊的代碼。請記住,緊湊的代碼並不總是一件好事,特別是如果它使代碼難以理解。如果您想了解更多有關語言的「技巧」,請參考[官方Python教程](https://docs.python.org/3/tutorial/index.html) – Tryph

+0

感謝您的超級寶貴信息!我已經完成了教程,但我仍然在學習:)對不起,如果我要求很多,但是可以使用上述('一,二,三= item_list + [「未知」] *(3 - (item_list))')列表中的列表(?)(所以'item_list = [(「Get this string」,23),(「Get this string too」,52)]''如果我使用'one,two ,3 = item_list + [「unknown」] *(3-len(item_list))'在這種情況下,它返回'one =(「Get this string」,23)'而不是'one =「獲取該字符串」' – Sen

0

item_list[1]將立即提出一個錯誤,如果沒有列表中的2個元素;該行爲不像Clojure這樣的語言,而是返回空值。

改爲使用len(item_list) > 1

2

Python會拋出這個錯誤。所以,一個空數組不會有索引0

if item_list:  # an empty list will be evaluated as False 
    one = item_list[0] 
else: 
    one = "Unknown" 

if 1 < len(item_list): 
    two = item_list[1] 
else: 
    two = "Unknown" 

if 2 < len(item_list): 
    three = item_list[2] 
else: 
    three = "Unknown" 
0

你需要檢查,如果你的列表足夠長,以便在你正試圖從檢索索引位置的值。如果您還試圖避免在條件語句中使用else,則可以使用默認值預先分配變量。

count = len(item_list) 
one, two, three = "Unknown", "Unknown", "Unknown" 
if count > 0: 
    one = item_list[0] 
if count > 1: 
    two = item_list[1] 
if count > 2: 
    three = item_list[2]