【问题标题】:list index out of range for while loopwhile循环的列表索引超出范围
【发布时间】:2017-12-01 14:41:15
【问题描述】:
def main():
    infile = open('charge_accounts.txt', 'r')
    chargeAccounts = infile.readlines()

    index = 0
    while index < len(chargeAccounts):
        chargeAccounts[index] = chargeAccounts[index].rstrip('\n')
        index += 1

    userAccount = input("Please enter a charge account number: ")

    count = 0
    while userAccount != chargeAccounts[count] or chargeAccounts[count] == chargeAccounts[17]:
        count += 1


    if chargeAccounts[index] == userAccount:
        print("The account number", userAccount, "is in the list.")
    else:
        print("The account number", userAccount, "in not in the list.")


main()

我正在尝试在 python 中编写一个代码,让用户输入一个数字并检查该数字是否在列表中。当我尝试运行此代码时,我收到一条错误消息,指出列表索引在 while 循环中超出范围。列表中只有 18 个项目,我将 while 循环设置为在 17 处终止(列表中应该是 18)。 编辑:如果将 while 循环设置为 chargeAccounts[count] != chargeAccounts[17]:

,它也不起作用

这是确切的错误代码:

Traceback (most recent call last):
  File "F:/CPT 168/Ch 7/AndrewBroughton_Chapter7_Excersizes/7-5/7-5.py", line 23, in <module>
    main()
  File "F:/CPT 168/Ch 7/AndrewBroughton_Chapter7_Excersizes/7-5/7-5.py", line 13, in main
    while userAccount != chargeAccounts[count] or chargeAccounts[count] != chargeAccounts[17]:
IndexError: list index out of range

这是原始文本文件的内容:

5658845
4520125
7895122
8777541
8451277
1302850
8080152
4562555
5552012
5050552
7825877
1250255
1005231
6545231
3852085
7576651
7881200
4581002

【问题讨论】:

  • 您有几个 while 循环,发布您的确切错误代码并通过向我们提供原始数据使问题可重现。似乎您在不检查它是否低于chargeAccount 长度的情况下增加计数。您应该在 while 循环的其他条件之前检查它。
  • chargeAccounts[17] 闻起来很臭。
  • 那么len(chargeAccounts)的值是多少?

标签: python python-3.x


【解决方案1】:

只要条件为True,while 循环就会一直循环。

count = 0
while userAccount != chargeAccounts[count] or chargeAccounts[count] == chargeAccounts[17]:
    count += 1

如果我在您的程序中输入了无效的userAccount,则条件userAccount != chargeAccounts[count] 的第一部分将始终为True。这使得整个条件为True,因为您使用的是or 逻辑。

此外,如果您想检查是否已到达列表末尾,则不必检查最后一个列表元素 (chargeAccounts[count] == chargeAccounts[17]) 的内容。请改为检查长度 (count == len(chargeAccounts))。

要解决此问题,请将循环条件更改为类似

while count < len(chargeAccounts) and userAccount != chargeAccounts[count]:

(我不确定这是否正是您所需要的,因为我并没有真正遵循您程序的逻辑。不过,这应该可以让您摆脱当前的错误。)

【讨论】:

  • 修复了while循环,但现在我得到了同样的错误“如果chargeAccounts [count] == userAccount:如果我输入了正确的数字,但不是错误的数字。
  • @AndrewWilliamBroughton print indexcount 的值以查找它们超出列表范围的位置。
  • 它说计数是 18,奇怪。
  • 好的,我通过添加一个 if 语句来修复它,如果它超过 17 则将计数更改为 0。谢谢
【解决方案2】:

您在字符串if chargeAccounts[index] == userAccount: 处收到错误,因为index 已经大于列表的最后一个元素的索引(因为您在上面的这个index 离开了循环)。

我建议您遵循一些规则来使用列表,这可以使您避免出现类似的索引错误。

  1. 如果您线性遍历每个元素,请使用 for-loop 而不是 while-loop。
  2. 如果您想离开循环并保留索引,请使用break

所以你的代码可能看起来像这样:

with open('charge_accounts.txt', 'r') as infile:
    chargeAccounts = infile.readlines()

for index in range(len(chargeAccounts)):
    chargeAccounts[index] = chargeAccounts[index].strip()

userAccount = input("Please enter a charge account number: ")

found = False
for chargeAccount in chargeAccounts:
    if chargeAccount = userAccount:
        found = True
        break

if found:
    print("The account number", userAccount, "is in the list.")
else:
    print("The account number", userAccount, "in not in the list.")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-03
    • 2019-05-21
    相关资源
    最近更新 更多