我尝试从 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)) 我得到 p>
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/