gpt4 book ai didi

python - 值错误 : invalid literal for int() with base 10: ''

转载 作者:太空宇宙 更新时间:2023-11-04 01:26:13 25 4
gpt4 key购买 nike

我是 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

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

最佳答案

尝试读取文件末尾后,您将得到一个空字符串 '',它无法转换为 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

关于python - 值错误 : invalid literal for int() with base 10: '' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17704652/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com