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

标签 python arrays

我尝试从 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/

相关文章:

python - 我应该将产品图像存储为 db.ListProperty(db.Blob) 还是 db.ListProperty(db.Key)?

python - 如何使用opencv找到图像中所有圆圈的所有接触点

java - 将二维数组值更改为零

计算数组中整数的总和

c# - C++/C#数组内存异常

c++ - 我收到 [Error] 'Eintrag' does not name a type 我不知道为什么

java - Arrays.sort从较高的数字到较低的数字?

python - Pandas 数据框范围索引

Python - 以更高效的方式遍历大量文件

python - 如何创建一个新字典,其键是来自另一个字典的键?不可散列类型错误