【问题标题】:Python: "list index out of range" when attempting to do a loop that chooses random numbersPython:尝试执行选择随机数的循环时“列表索引超出范围”
【发布时间】:2018-10-18 08:39:07
【问题描述】:

我的任务是随机分配具有名称和四个类别的卡片,然后将它们从文本文件中取出并将完成的卡片保存回另一个文本文件。随机卡片的数量取决于用户输入,但它只会在显示此错误之前循环几次。

  line 35, in <module>
  exercise = lines5[exerlinenum]
IndexError: list index out of range

这是我正在使用的代码。

x = 0
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 
20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
user = int(input("Please enter your even number: "))
if user % 2 == 0:
     answer = list.index(user)
     split_list = list[0:answer+1]
     loop = len(split_list)

else:
     print("Input not even!")
     import random
     while x < loop:

         file = open("dognames.txt", "r")
         lines1=file.readlines()
         namelinenum=random.randint(0, 17)
         dogname = lines1[namelinenum]
         print("Name:", dogname)

         file2 = open("friendliness.txt", "r")
         lines2=file2.readlines()
         frenlinenum=random.randint(0, 10)
         friendliness = lines2[frenlinenum]
         print("Friendliness:", friendliness)

         file4 = open("intelligence.txt", "r")
         lines4=file4.readlines()
         intlinenum=random.randint(0, 100)
         intelligence = lines4[intlinenum]
         print("Intelligence:", intelligence)

         file5 = open("exercise.txt", "r")
         lines5=file5.readlines()
         exerlinenum=random.randint(0, 5)
         exercise = lines5[exerlinenum]
         print("Exercise:", exercise)

         file6 = open("drool.txt", "r")
         lines6=file6.readlines()
         droollinenum=random.randint(0, 10)
         drool = lines6[droollinenum]
         print("Drool:", drool)

         doginfo=(dogname, friendliness, intelligence, exercise, drool)
         file3 = open("dogs.txt", "a")
         file3.write(repr(doginfo))



         x += 1

    file3.close()

这里是有问题的文本文件,如果有帮助的话。

dognames.txt

 Jack
 Harry
 Lyla
 Lucky
 Ringo
 Sadie
 Pinkie
 Teddy
 Simrin
 Andie
 Willow
 Luna
 Bailey
 Zoey
 Checkers
 Cheddar
 Arlo
 Humphrey

友好性.txt

1
2
3
4
5
6
7
8
9
10

智能.txt

1
2
3
4
5
6
7
8
9
10
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
32 
33 
34 
35 
36 
37 
38 
39 
40 
41 
42 
43 
44 
45 
46 
47 
48 
49 
50 
51 
52 
53 
54 
55 
56 
57 
58 
59 
60 
61 
62 
63 
64 
65 
66 
67 
68 
69 
70 
71 
72 
73 
74 
75 
76 
77 
78 
79 
80 
81 
82 
83 
84 
85 
86 
87 
88 
89 
90 
91 
92
93
94 
95
96
97 
98
99
100

练习.txt

1
2
3
4
5

流口水.txt

1
2
3
4
5
6
7
8
9
10

非常感谢,请对我放轻松。我是初学者。

【问题讨论】:

  • 生成一个随机数 n 以读取仅包含数字 n 的文本文件的第 n 行有什么意义?我不清楚这其中的逻辑。
  • 如果你想学习如何写更多地道的python,请发帖codereview.stackexchange.com,你可以做得更好,我相信那里的人会给你一个很好的解释
  • @chris - 直到它正常工作。 Code Review 不喜欢看到已知损坏的代码。
  • @TobySpeight 如果不是很明显这是分开的,假设他先听了下面的答案

标签: python loops indexing


【解决方案1】:

函数random.randint(a,b) 返回一个随机数,包括ab。因此,在您的情况下,它可以返回 0 到 5 之间的随机数。

在 python 和大多数语言中,列表索引从 0 开始。所以您的 lines5 列表大小为 5,索引从 0 到 4。请将第 35 行更改为此 -

exerlinenum=random.randint(0, 4)

它应该可以正常工作。 您还需要将所有 random.randint() 调用中的第二个参数减少 1,这样您就不会看到此错误。

【讨论】:

  • 似乎所有其他列表都存在同样的问题,但由于它们更大,您获得错误的机会更少
【解决方案2】:

问题是如果exerlinenum=random.randint(0, 5)5,那么索引超出范围,因为exercise.txt 只有5 个条目。 (记住,python 以0 开始计算索引)

看看你的其他行你有同样的问题。 (例如,智力没有 101 个条目,而只有 100 个。)您很可能只在锻炼时看到它,因为从 6 个中获得 5 个的概率大于在 101 个可能性中获得 100 个的概率。

【讨论】:

    【解决方案3】:

    您正在尝试访问名为lines5 的列表中的元素。此列表包含从exercise.txt 读取的 5 个元素。

    在python中,计数从0开始,所以如果你想访问列表的第一个元素,你可以使用lines5[0]。如果您扩展此逻辑,您将看到lines5[4] 为您提供lines5 的第5 个元素,而lines5[5] 将尝试访问您的列表中不存在的第6 个元素。

    然后,您的代码示例使用random.randint(0, 5) 选择一个随机数。此随机数用于访问lines5 的元素。 random.randint(0, 5) 可能返回 0、1、2、3、4 或 5!如果它碰巧返回一个 5,你会被击中

    IndexError: 列表索引超出范围

    因为lines5 仅包含 5 个元素,而您正在尝试访问第 6 个元素!

    您可以解决您的问题,方法是使用random.randint(0, 4) 正在向exercise.txt 添加额外的一行

    【讨论】:

      【解决方案4】:

      另一个答案说明了您收到错误的原因 - 由于随机库函数返回值。更通用的是,为了摆脱“列表索引超出范围”错误,在访问列表项之前检查索引是安全的。例如,

      if line5: # make sure the list is not empty
          if exerlinenum >= len(line5): # index out of range
              # throw error or what ever
          else:
              exercise = lines5[exerlinenum]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-10-03
        • 1970-01-01
        • 1970-01-01
        • 2019-12-17
        • 2020-07-23
        • 2022-09-23
        • 2012-11-13
        • 1970-01-01
        相关资源
        最近更新 更多