簡體   English   中英

Python TypeError:整數是必需的(got類型列表)

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM