列表索引超出Python范围。没有任何作用

时间:2016-02-06 17:20:03

标签: python

我已经审核了多个主题,并回答了我的问题。无论我尝试什么,似乎都没有任何效果。

我正在尝试创建100个随机数,并将这些随机数放入列表中。但是我一直在

File "E:\WorkingWithFiles\funstuff.py", line 17, in randNumbs
    numbList[index]+=1
IndexError: list index out of range

我的代码是:

def randNumbs(numbCount):
    numbList=[0]*100
    i=1
    while i < 100:
        index = random.randint(1,100)
        numbList[index]+=1
        i+=1
    print (numbList)
    return (numbList)

在审查多个线程并修补我之后,似乎无法得到答案。

在我继续这之前是项目的范围: 我有一个.txt文件,它包含一个字典,但是里面有很多单词。首先,我编写一个函数来计算.txt文件中有多少单词。其次,我在1和.txt文件中的单词数量之间生成100个随机数。最后,我需要创建一个打印

的.txt文件
"Number   Word"
 120      Bologna 

等等。我无法生成随机数。如果有人知道为什么我的列表索引超出范围以及如何提供帮助,所有帮助将不胜感激!谢谢!

编辑:.txt文件长度为113k字

4 个答案:

答案 0 :(得分:3)

你在这里列出了100号的名单:

numbList=[0]*100

您的问题是,当您应该访问索引0-99时,您创建的索引从1到100。给定大小n的列表,有效列表索引为0n-1

将您的代码更改为

index = random.randint(0,99)

答案 1 :(得分:0)

看起来像是一个错误的错误。 randint将返回数字1到100,而列表的索引为0到99。

此外,您可以像这样重写代码:

def randNumbs(numbCount):
    return [random.randint(1, 100) for i in range(numbCount)]

答案 2 :(得分:0)

我会稍微改变一下这个问题:

from random import sample

SAMPLE_SIZE = 100

# load words
with open("dictionary.txt") as inf:
    words = inf.read().splitlines()   # assumes one word per line

# pick word indices
# Note: this returns only unique indices,
#   ie a given word will not be returned twice
num_words = len(words)
which_words = sample(range(num_words), SAMPLE_SIZE)
# Note: if you did not need the word indices, you could just call
#   which_words = sample(words, SAMPLE_SIZE)
# and get back a list of 100 words directly

# if you want words in sorted order
which_words.sort()

# display selected words
print("Number   Word")
for w in which_words:
    print("{:6d}   {}".format(w, words[w]))

给出类似

的内容
Number   Word
   198   abjuring
  2072   agitates
  2564   alevin
  6345   atrophies
  8108   barrage
  9155   begloom
 10237   biffy
 11078   bleedings
 11970   booed
 14131   burials
 14531   cabal
# etc...

答案 3 :(得分:0)

在这里,我试图修复你的代码。评论中的解释。

import random

def rand_numbs(numb_count):

    # this will generate a list of length 100
    # it will have indexes from 0 to 99

    numbList = [0] * 100

    # dont use a while loop...
    # when a for loop will do

    for _ in range(numb_count):

    # randint(i, j) will generate a number
    # between i and j both inclusive!
    # which means that both i and j can be generated

        index = random.randint(0, 99)

    # remember that python lists are 0-indexed
    # the first element is nlist[0]
    # and the last element is nlist[99]
        numbList[index] += 1

    print (numbList)
    return (numbList)