简体   繁体   中英

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

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

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) .
Make sure to convert the content you read from the file to int prior to doing the myArray.fromlist(l) call.

Assuming your file contains one number per line, you could change the assignment to sclist to:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM