【问题标题】:List index out of range (python)列表索引超出范围(python)
【发布时间】:2012-11-11 23:09:53
【问题描述】:

我正在创建一个用于玩字谜的单词生成器,它可以运行大约六个单词,然后显示“列表索引超出范围”。

这是我的代码:

def selection(word):
    while True:
        from random import randint
        sel = randint(1,10)
        print(word[sel])
        input("\nPress enter to select a new word.")

print("Type in ten words to add to the list.")
words = []
words.append(input("1st word: "))
words.append(input("2nd word: "))
words.append(input("3rd word: "))
words.append(input("4th word: "))
words.append(input("5th word: "))
words.append(input("6th word: "))
words.append(input("7th word: "))
words.append(input("8th word: "))
words.append(input("9th word: "))
words.append(input("10th word: "))
input("\nPress enter to randomly select a word.")
selection(words)

【问题讨论】:

  • 您在循环中重复导入randint 是否有任何具体原因?

标签: python list indexing range


【解决方案1】:

您目前正在选择介于 110 之间的数字,包括两者。 Python 列表是0 indexed,因此您应该在09 之间选择一个数字。

sel = randint(0, 9)

这也是使用choice() 函数的好地方。它从一个序列(例如一个列表)中选择一个随机元素。

random_word = random.choice(words)

【讨论】:

  • 另外,如果我想让它让用户可以输入任意数量的单词,我如何让它只选择其中一个单词而不是 1 和某个指定数字之间的一个?
  • @CharlieKimzey,random.choice。请注意,您可以只传递一个单词列表。你不需要告诉choice有多少字。
【解决方案2】:

另外,这不是一个真正的答案,但你可以做

for i in xrange(0, 9):
    words.append(input("{0}st word: ".format(i + 1))

还有

random.choice

【讨论】:

  • 你能解释一下这是做什么的吗?
  • 将不起作用 - 因为生成从 0 到 8 的值,包括 - 9 将被遗漏
  • 这将打印像“2st word”这样的行
猜你喜欢
  • 2015-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多