簡體   English   中英

異常處理 - 列表索引超出范圍

[英]Exception Handling - list index out of range

我有一個列表,其中列表的長度是動態的。 如果我們看下面的例子,列表的長度是 2 從 0 開始。我在 excel 表中填寫這個值,當列表的長度為 6 時它工作正常,但有時列表的長度是2 或 3 和那個時間點,我得到預期的“列表索引超出范圍”。 如果列表超出范圍,我需要填寫 0 作為其中 rest 的值。 我們應該怎么做?

counts = [2, 1] #list

df1.loc[0, 'Value'] = counts[0]
df1.loc[1, 'Value'] = counts[1]
df1.loc[2, 'Value'] = counts[2]
df1.loc[3, 'Value'] = counts[3]
df1.loc[4, 'Value'] = counts[4]
df1.loc[5, 'Value'] = counts[5]

錯誤:

df1.loc[2, 'Value'] = counts[2]
IndexError: list index out of range

預期成績

df1.loc[0, 'Value'] = 2
df1.loc[1, 'Value'] = 1
df1.loc[2, 'Value'] = 0
df1.loc[3, 'Value'] = 0
df1.loc[4, 'Value'] = 0
df1.loc[5, 'Value'] = 0

在列表中找到原始列表和 append 0s 的長度

append_len = 6 - len(count)
for i in range(append_len):
    count.append(0)


for i in range(6):
    df1.loc[i, 'Value'] = counts[i]

輸入數據:

>>> df1
       Key
0     Mike
1     John
2   Arnold
3   Freddy
4  Georges
5     Paul

Value列:

df1["Value"] = counts + [0] * (len(df1) - len(counts))

Output 結果:

>>> df1
       Key  Value
0     Mike      2
1     John      1
2   Arnold      0
3   Freddy      0
4  Georges      0
5     Paul      0

http://docs.python.org/3/tutorial/errors.html?highlight=errors#handling-exceptions

例子:

dictionary = {0: None, 1: None, 2: None, 3: None, 4: None, 5: None}
counts = [2, 1] #list

for i in range(len(dictionary)):
    try:
        dictionary[i] = counts[i]
    except IndexError:
        dictionary[i] = 0

for key, value in dictionary.items():
    print(key, value)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM