[英]Python TypeError: an integer is required (got type list)
我试图从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'
这里的问题是l = f.readlines()
将返回一个字符串列表,然后将其放入另一个列表sclist = [l]
,所以也可以执行myArray.fromlist(l)
。
在进行myArray.fromlist(l)
调用之前,请确保将从文件中读取的内容转换为int。
假设您的文件每行包含一个数字,则可以将对sclist的分配更改为:
sclist = [int(s) for s in l]
希望这会起作用。 我还建议您避免使用“列表”作为变量名(在此示例中未使用),因为这会掩盖标准的Python定义,并可能引起混淆。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.