Home >> Blog >> 錯誤 list index out of range 是什麼意思?

先放下手中的SEO搜尋引擎優化案件,讓我們來討論"錯誤 list index out of range " 是什麼意思。

錯誤 list index out of range 是什麼意思?

我們將在下面列出程式碼,它show出我們認為應該是正確答案的內容:

MichaelLieberman None 但是,又收到錯誤“糟糕,再試一次!您的函數導致以下錯誤:list index out of range“但不知道為什麼。另外,為什麼如果我們得到正確的輸出,但為何實際上無法通過這個級別?

n = ["Michael", "Lieberman"]
# Add your function here

def join_strings(x):
return x[0] + x[1]

print join_strings(n)

由於沒有人回答這個問題,而且你可能已經通過了這個練習,我們仍然會回答讓其他人看到。

通常,list index out of range意味著您提供的索引不存在列表元素。

現在,對於這個練習,他們要求您為列表中未知數量的字符串(即列表中的任意數量的字符串)創建一個通用函數,而不僅僅是練習中提供的 2 個字符串。如果列表中有 3 個字符串,您的函數將不起作用。

因此,此練習需要您創建一個for循環,以遍歷提供的任何列表中的每個字符串。該n = ["Michael", "Lieberman"]列表僅用於測試目的;不要基於該列表創建函數。

希望有幫助!:)

不知道為什麼你得到錯誤。我沒有面對這個:

>>> n = ['a','b']
>>> def joy(x):
... return x[0]+x[1]
...
>>> print joy(n)
ab
>>> n= ['a','b','c']
>>> print joy(n)
ab
>>> n = ['Michael', 'Lieberman']
>>> print joy(n)
MichaelLieberman
>>> n = ['Michael', 'Lieberman', 'Python']
>>> print joy(n)
MichaelLieberman
>>>