两个列表的比较:"列表索引超出范围"

时间:2015-10-01 10:57:32

标签: python

我有以下列表:

first_list = [25.26, 1.74, 6.07, 7.38, 1.58, 0.71, 0.49, 0.71, 3.94]
second_list = [28.15, 1.28, 7.31, 8.58, 2.09, 0.21, 0.43, 0.83, 4.39]

以下功能

for num in range(0,9):
    list_one_score = 0
    list_two_score = 0
    if first_list[num] > second_list[num]:
        list_one_score += 1
    else:
        list_two_score += 1

每次运行此代码时,我都会得到" IndexError:列表索引超出范围"而且我不明白为什么。请帮忙。

3 个答案:

答案 0 :(得分:2)

您可以简化循环

for item_one, item_two in zip(first_list, second_list):
    if item_one > item_two:
        list_one_score += 1
    else:
        list_two_score += 1

这将采用您的两个列表,将它们配对,并迭代结果。这将阻止您获取IndexError

您的示例与您在本地运行的内容完全相同吗?

答案 1 :(得分:1)

使用此代码,范围正确。

first_list = [25.26, 1.74, 6.07, 7.38, 1.58, 0.71, 0.49, 0.71, 3.94]
second_list = [28.15, 1.28, 7.31, 8.58, 2.09, 0.21, 0.43, 0.83, 4.39]

list_one_score = 0
list_two_score = 0

for num in range(0,9):
    if first_list[num] > second_list[num]:
        list_one_score += 1
    else:
        list_two_score += 1
print(list_one_score)
print(list_two_score)

#Or Remove the Index only by this logic
for a,b in in zip(first_list, second_list):
    if a > b:
        list_one_score += 1
    else:
        list_two_score += 1

答案 2 :(得分:0)

不知道为什么会得到IndexError

'''
list_number.py
'''

#declare variables
first_list = [25.26, 1.74, 6.07, 7.38, 1.58, 0.71, 0.49, 0.71, 3.94]
second_list = [28.15, 1.28, 7.31, 8.58, 2.09, 0.21, 0.43, 0.83, 4.39]
list_one_score = 0
list_two_score = 0

#loop
for num in range(0,9):
    if first_list[num] > second_list[num]:
        list_one_score += 1
    else:
        list_two_score += 1

#Print
print '''
score list 1 = %d
score list 2 = %d
''' % (list_one_score, list_two_score)
相关问题