簡體   English   中英

如何僅從字符串列表中提取浮點數?

[英]How do I extract only floats from a list of strings?

output = []
stuff = ['candy', '1.3', '1.23']
floats = map(float, stuff[1:])
tuples = (stuff[0], floats)
output.append(tuples)
print(output)

它沒有按預期打印出[('candy',[1.3,1.23])] ,而是打印出:

[('candy', <map object at 0x00000000038AD940>)]

我不知道出了什么問題,請告訴我修復程序。

您的問題是您沒有將map轉換為列表,請嘗試以下操作:

output = []
stuff = ['candy', '1.3', '1.23']
floats = map(float, stuff[1:])
tuples = (stuff[0], list(floats))
output.append(tuples)
print(output)

>>> output = []
>>> stuff = ['candy', '1.3', '1.23']
>>> floats = map(float, stuff[1:])
>>> tuples = (stuff[0], list(floats))
>>> output.append(tuples)
>>> print(output)
[('candy', [1.3, 1.23])]
>>> 

在 Python3 map返回一個map object

這是你可以在 Python3 中實現你想要的方式:

floats = list(map(float, stuff[1:]))

輸出:

[('candy', [1.3, 1.23])]

這是地圖的 Python 2 評估:

Python 2.7.10 (default, Jun 10 2015, 19:42:47) 
[GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> map(float, ['1.1','1.2'])
[1.1, 1.2]

這是一個 Python3 懶惰的地圖評估:

Python 3.4.3 (default, Jun 10 2015, 19:56:14) 
[GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> map(float, ['1.1','1.2'])
<map object at 0x103da3588>

你看到的是因為你在 Python 3 上運行你的代碼。用list包裹來修復。

暫無
暫無

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

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