2

我是 Python 新手,我不知道为什么有时会出现此错误。

这是代码:

import random
sorteio = []
urna = open("urna.txt")

y = 1
while y <= 50:
    sort = int(random.random() * 392)
    print sort
    while sort > 0:
        x = urna.readline()
        sort = sort - 1
    print x  
    sorteio = sorteio + [int(x)]
    y = y + 1
print sorteio

其中 urna.txt 是这种格式的文件:

1156
459
277
166
638
885
482
879
33
559

如果有人知道为什么会出现此错误以及如何修复它,我将不胜感激。

4

2 回答 2

2

在尝试读取文件末尾之后,您会得到一个''无法转换为 int 的空字符串。

>>> int('')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ''

如果我正确理解您的问题,以满足从文本值中选择 50 行随机行的要求:

import random

with open("urna.txt") as urna:
    sorteio = [int(line) for line in urna] # all lines of the file as ints

selection = random.sample(sorteio, 50)

print selection
于 2013-07-17T18:37:52.610 回答
1

.readline()当您到达文件末尾时返回一个空字符串,这不是一个有效数字。

测试它:

if x.strip():  # not empty apart from whitespace
    sorteio = sorteio + [int(x)]

您似乎正在添加到列表中;列表有一个方法:

sorteio.append(int(x))

如果您想从文件中获取随机样本,有更好的方法。一种是读取所有值,然后使用random.sample(),或者您可以在逐行读取文件时选择值,同时调整下一行是样本一部分的可能性。有关该主题的更深入讨论,请参阅我以前的答案。

于 2013-07-17T16:00:24.270 回答