gpt4 book ai didi

Python 类型错误 : an integer is required (got type list)

转载 作者:行者123 更新时间:2023-12-01 04:24:59 25 4
gpt4 key购买 nike

我尝试从 num.txt(1 3 2) 中获取数字并将其设置为数组

from array import *
import sys
f = open('num.txt', 'r')
l = f.readlines()
f.close()
list = [1, 2, 3, 4, 5 ,6]
sclist = [l]
myArray = array('i', [])
myArray.fromlist(sclist)
for i in myArray:
print(i)

返回

TypeError: an integer is required (got type list)   

如果我将其更改为 myArray.fromlist(int(sclist)) 我得到

TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'    

最佳答案

假设您的文件每行包含一个数字,您可以将 sclist 的分配更改为:

sclist = [int(s) for s in l]

希望这会起作用。我还建议您避免使用“list”作为变量名(本示例中未使用),因为这会掩盖标准 Python 定义并可能导致困惑。

关于Python 类型错误 : an integer is required (got type list),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33257388/

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