简体   繁体   English

异常处理 - 列表索引超出范围

[英]Exception Handling - list index out of range

I have a list where the length of the list is dynamic.我有一个列表,其中列表的长度是动态的。 If we look at the below example, the length of the list is 2 starts from 0. I am filling in this value in an excel sheet and it works fine when the length of the list is 6 but at times the length of the list is 2 or 3 and that point of time, I get "list index out of range" which is expected.如果我们看下面的例子,列表的长度是 2 从 0 开始。我在 excel 表中填写这个值,当列表的长度为 6 时它工作正常,但有时列表的长度是2 或 3 和那个时间点,我得到预期的“列表索引超出范围”。 If the list is out of range, I need to fill in 0 as the Value for rest of them.如果列表超出范围,我需要填写 0 作为其中 rest 的值。 How can we do this?我们应该怎么做?

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]

Error:错误:

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

Expected Results预期成绩

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

find the length of original list and append 0s in the list在列表中找到原始列表和 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]

Input data:输入数据:

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

Assign Value column: Value列:

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

Output result: 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 http://docs.python.org/3/tutorial/errors.html?highlight=errors#handling-exceptions

example:例子:

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