gpt4 book ai didi

python - 对于仅包含整数的文件,基数为 10 的 int() 的文字无效

转载 作者:行者123 更新时间:2023-11-30 23:36:11 25 4
gpt4 key购买 nike

rows = []
FILE = open("testing.txt", "r")
for blob in FILE: rows.append([int(i) for i in blob.split(" ")])

这里的testing.txt包含

01 23 04   05 67
08 09 10
11
12

但是当我运行代码时,出现以下错误:

ValueError                                Traceback (most recent call last)
<ipython-input-1-2086c8bf9ab4> in <module>()
1 rows = []
2 FILE = open("testing.txt", "r")
----> 3 for blob in FILE: rows.append([int(i) for i in blob.split(" ")])

ValueError: invalid literal for int() with base 10: ''

所以我的问题是:int() 有什么问题?我认为如果参数是整数就完全没问题(例如 int(5) == 5)。谢谢。

最佳答案

如前所述,问题是换行符。

我建议使用split()而不是split("")。这会将所有空格视为分隔符,包括换行符。因此,您将避免在 \n 上调用 int()

关于python - 对于仅包含整数的文件,基数为 10 的 int() 的文字无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16751460/

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