【问题标题】:index out of range raises in random function [duplicate]随机函数中超出范围的索引[重复]
【发布时间】:2015-12-26 21:38:49
【问题描述】:

我有这个功能,它只是打开一个文本文件并读取行:

def select_word(model):
    lines = model.read().splitlines()
    selectedline = random.choice(lines)
    return [selectedline.split(":")[0],selectedline.split(":")[1]]

当我只为一个调用这个函数时,没有问题。但是当我不止一次调用它时:

print select_word(a)
print select_word(a)
print select_word(a)
print select_word(a)
print select_word(a)

我收到了这个错误:

Traceback (most recent call last):
  File "wordselect.py", line 58, in <module>
    print select_word("noun")   
  File "wordselect.py", line 19, in select_word
    selectedline = random.choice(lines)
  File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/random.py", line 275, in choice
    return seq[int(self.random() * len(seq))]  # raises IndexError if seq is empty
IndexError: list index out of range

这个函数有什么问题?

【问题讨论】:

  • 你的函数没有打开任何文件..
  • 不打开,我在另一个地方定义了这个模型。一次通话即可使用
  • 你应该在你的函数中打开你的文件......所以再次......你的函数没有打开任何文件!
  • 什么是a in print select_word(a) BTW?
  • 那是机密...

标签: python


【解决方案1】:
import random

def select_word(model):
    with open(model, 'r') as f:
        lines = f.read().splitlines()
    selectedline = random.choice(lines)
    return [selectedline.split(":")[0],selectedline.split(":")[1]]

result = select_word('example.txt')
print result

我这样做了,没有遇到问题。 只需确保在您打开的文件中有类似的内容。

Line: 1
Line: 2

【讨论】:

    【解决方案2】:

    random.choice 引发 IndexError 如果你传递一个空序列。当您第二次在文件对象上调用.read() 时会发生这种情况(您只能执行一次,后续调用将返回一个空字符串)。

    要修复该函数,您可以读取文件一次,然后将行传递给函数,例如:

    lines = list(model)
    
    def select_word(lines):    
        selectedline = random.choice(lines)
        return selectedline.split(":", 1)
    

    【讨论】:

      【解决方案3】:

      文件句柄像生成器一样运行。读取文件后,您已到达流的末尾。

      model.seek(0) # bring cursor to start of file after reading, at 2nd line of the function
      

      【讨论】:

      • 那我该怎么办?
      • 我在不同的python文件中打开文件并导入了这个我认为会导致问题的文件吗?
      • 实际上它解决了问题,但我不知道如何
      • 如果您正在阅读一本书并且到达最后一页,还有什么要读的吗?不,就是这样。这是行的尽头。如果你想继续阅读,你需要从最前面开始。代码中的相同。
      猜你喜欢
      • 1970-01-01
      • 2014-04-11
      • 1970-01-01
      • 2020-02-13
      • 1970-01-01
      • 2012-08-24
      • 2015-06-20
      • 2018-09-03
      • 2021-11-13
      相关资源
      最近更新 更多