【发布时间】:2021-09-02 07:52:21
【问题描述】:
我有一些代码从字典中获取键和值,在这个例子中将它们打印在嵌套的 for 循环中。只要每个键都有一个正确的值列表,它就可以工作。当一个键有一个空列表时,我得到一个 IndexingError 'index list out of range'。在这种情况下我应该使用什么方法来索引。
代码有5行生成测试字典,当我使用测试行时失败了2,3,4 - 5就可以了。
键的值不能改变,它们在更大的代码中的其他地方使用。
代码
# TEST LINES
user_return_dict = {1:[1, 2, 3], 2:[501, 555, 999], 3:[1111, 1002, 1499, 1500], 4:[1501, 1999, 2000]}
#user_return_dict = {1:[], 2:[501, 555, 999], 3:[1111, 1002, 1499, 1500], 4:[1501, 1999, 2000]}
#user_return_dict = {1:[1, 2, 3], 2:[], 3:[1111, 1002, 1499, 1500], 4:[1501, 1999, 2000]}
#user_return_dict = {1:[1, 2, 3], 2:[501, 555, 999], 3:[], 4:[1501, 1999, 2000]}
#user_return_dict = {1:[1, 2, 3], 2:[501, 555, 999], 3:[1111, 1002, 1499, 1500], 4:[]}
lines_to_test = [k for k,v in user_return_dict.items() if v]
holes_to_test = [v for k,v in user_return_dict.items() if v]
print("lines_to_test : ", lines_to_test )
holes_to_test = [v for k,v in user_return_dict.items() if v]
print("holes_to_test : ", holes_to_test )
for test_row in lines_to_test:
print("test_row : ", test_row)
print(" holes to test : ", holes_to_test[test_row - 1])
退货
lines_to_test : [1, 2, 3]
holes_to_test : [[1, 2, 3], [501, 555, 999], [1111, 1002, 1499, 1500]]
test_row : 1
holes to test : [1, 2, 3]
test_row : 2
holes to test : [501, 555, 999]
test_row : 3
holes to test : [1111, 1002, 1499, 1500]
使用这些测试行时列表索引错误失败
#user_return_dict = {1:[], 2:[501, 555, 999], 3:[1111, 1002, 1499, 1500], 4:[1501, 1999, 2000]}
#user_return_dict = {1:[1, 2, 3], 2:[], 3:[1111, 1002, 1499, 1500], 4:[1501, 1999, 2000]}
#user_return_dict = {1:[1, 2, 3], 2:[501, 555, 999], 3:[], 4:[1501, 1999, 2000]}
追溯
The script terminated with an unhandled error.
IndexError: list index out of range ... line 18 # the last line
【问题讨论】: