[英]Converting list of list of strings into list of list of integers
listX = [['0,0,0,3,0,4,0,3'], ['0,0,0,0,0,3,0,7'], ['0,0,1 ,0,0,5,0,4'], ['0,0,0,1,3,1,0,5'], ['1,1,1,0,0,0,2,5 '], ['0,0,0,1,1,5,0,3'], ['0,0,0,5,3,0,0,2']]
我需要它到 output
[[0, 0, 0, 3, 0, 4, 0, 3], [0, 0, 0, 0, 0, 3, 0, 7], [0, 0, 1, 0, 0, 5, 0, 4], [0, 0, 0, 1, 3, 1, 0, 5], [1, 1, 1, 0, 0, 0, 2, 5], [0, 0, 0, 1, 1, 5, 0, 3], [0, 0, 0, 5, 3, 0, 0, 2]]
當我使用 listX = [[int(float(o)) for o in p] for p in listX] 我得到 ValueError: could not convert string to float: '0,0,0,3,0,4,0, 3'
您可以嘗試以下列表理解:
output = [[int(x) for x in re.findall(r'\d+', y[0])] for y in listX]
print(output)
這打印:
[[0, 0, 0, 3, 0, 4, 0, 3], [0, 0, 0, 0, 0, 3, 0, 7],
[0, 0, 1, 0, 0, 5, 0, 4], [0, 0, 0, 1, 3, 1, 0, 5],
[1, 1, 1, 0, 0, 0, 2, 5], [0, 0, 0, 1, 1, 5, 0, 3],
[0, 0, 0, 5, 3, 0, 0, 2]]
這使用嵌套列表推導。 外部理解將單元素 CSV integer 字符串輸入內部理解。 內部列表理解使用re.findall
在 CSV 列表中查找整數,一次一個。
您需要先拆分您擁有的每個字符串listX[i].split(",")
然后應用轉換
如果您有一個包含多個項目的列表列表,您可以嘗試以下(嵌套)列表理解:
output = [list(map(int, y.split(','))) for x in listX for y in x]
如果知道您的列表只包含一個項目,那么您只需要:
output = [list(map(int, x[0].split(','))) for x in listX]
鑒於您的輸入是
[['0,0,0,3,0,4,0,3'], ['0,0,0,0,0,3,0,7'],
['0,0,1,0,0,5,0,4'], ['0,0,0,1,3,1,0,5'],
['1,1,1,0,0,0,2,5'], ['0,0,0,1,1,5,0,3'],
['0,0,0,5,3,0,0,2']]
讓我們從在 處拆分它開始,
使用 split 方法並將整個內容轉儲到一個臨時數組中,比如x
。 代碼如下——
x=[]
[[x.append(j.split(",")) for j in i] for i in input]
print(x)
print(x)
語句僅用於調試和了解我的代碼的那部分是如何工作的。 您可以根據需要將其刪除。 現在我們執行將字符串列表轉換為整數列表並將其存儲在變量 say 'y' 中。 代碼如下 -
y = [[int(j) for j in i] for i in x]
print(y)
我的就地解決方案:
listX = list(map(lambda x: list(int(y) for y in x[0].split(',')), listX))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.