簡體   English   中英

從字符串列表中提取浮點數

[英]Extract floats from list of list of strings

[['1. (25, 32)'], ['2. (24.2, 31.5)'], ['3. (22, 34)'], ['4. (20.5, 34)']]

如何將括號之間的內容提取為浮點數。 output 應該是這樣的:

[[25, 32], [24.2, 31.5], [22, 34], [20.5, 34]]

從字符串中提取元組后將元組轉換為列表會消耗大量memory,並不理想。 如果您只想將元組的字符串轉換為浮點數。 你可以先做一個str.spliteval

[eval(j.split('. ')[1]) for i in alist for j in i]
[(25, 32), (24.2, 31.5), (22, 34), (20.5, 34)]

如果您的輸入始終采用這種格式,您可以執行以下操作:

your_input = [['1. (25, 32)'], ['2. (24.2, 31.5)'], ['3. (22, 34)'], ['4. (20.5, 34)']]
output = [[float(number) for number in elem[0].split(". ")[1].rstrip(")").lstrip("(").split(", ")] for elem in your_input]

output:

[[25.0, 32.0], [24.2, 31.5], [22.0, 34.0], [20.5, 34.0]]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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