简体   繁体   English

Python TypeError:整数是必需的(got类型列表)

[英]Python TypeError: an integer is required (got type list)

Im trying to take numbers from num.txt(1 3 2) and set it into a array 我试图从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)

It returns 它返回

TypeError: an integer is required (got type list)   

If I change it to myArray.fromlist(int(sclist)) I get 如果我将其更改为myArray.fromlist(int(sclist)),我会得到

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

Issue here is that l = f.readlines() will return a list of strings, which you then put in another list sclist = [l] , so just do myArray.fromlist(l) . 这里的问题是l = f.readlines()将返回一个字符串列表,然后将其放入另一个列表sclist = [l] ,所以也可以执行myArray.fromlist(l)
Make sure to convert the content you read from the file to int prior to doing the myArray.fromlist(l) call. 在进行myArray.fromlist(l)调用之前,请确保将从文件中读取的内容转换为int。

Assuming your file contains one number per line, you could change the assignment to sclist to: 假设您的文件每行包含一个数字,则可以将对sclist的分配更改为:

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

Hopefully that will work. 希望这会起作用。 I also suggest that you avoid using "list" as a variable name (unused in this example), since that will mask the standard Python definition and could cause confusion. 我还建议您避免使用“列表”作为变量名(在此示例中未使用),因为这会掩盖标准的Python定义,并可能引起混淆。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python:类型错误:需要一个整数(得到类型 str) - Python: TypeError: an integer is required (got type str) TypeError:Python中需要一个整数(类型为str) - TypeError: an integer is required (got type str) in python Python: TypeError: an integer is required (got type module) - Python: TypeError: an integer is required (got type module) Python:TypeError 需要 integer(获取类型 str) - Python: TypeError an integer is required(got type str) Python 2-如何修复TypeError:必须为整数(类型为str) - Python 2 - How to fix TypeError: an integer is required (got type str) Python多处理日志记录错误-TypeError:必须为整数(获取类型为NoneType) - Python Multiprocessing Logging Error - TypeError: an integer is required (got type NoneType) Python的HTTP请求:TypeError:需要一个整数(获取类型套接字) - HTTP request with Python : TypeError: an integer is required (got type socket) TypeError:需要一个 integer(获取类型元组)<python><opencv><tesseract></tesseract></opencv></python> - TypeError: an integer is required (got type tuple) <python> <OpenCV> <tesseract> Python - 类型错误:需要一个 integer(获取类型 datetime.datetime) - Python - TypeError: an integer is required (got type datetime.datetime) python / flask:TypeError:需要一个整数(得到类型str) - python/flask: TypeError: an integer is required (got type str)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM