【问题标题】:Alternative to regular list indexing常规列表索引的替代方案
【发布时间】: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

【问题讨论】:

    标签: python list indexing


    【解决方案1】:

    试试这个兄弟

    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 i, test_row in enumerate(lines_to_test):
        print("test_row : ", test_row)
        print("holes to test : ", holes_to_test[i])
    

    【讨论】:

    • 我可以看到这非常有效,但我不明白如何。在您的 for 循环中,“I”和“test_row”如何知道选择正确的索引?
    • 响应之前的@Windy71,通过你的循环头for test_row in lines_to_test,键值被影响到test_row。因此错误。在@sarat ravi 的答案循环标题for i, test_row in enumerate(lines_to_test) 中,每个列表元素的索引和键值都会影响到 i,test_row。在循环中,第一个 print 语句打印 key,第二个 print 语句在得到它后打印 value。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多