[英]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.