Python 如何仅从字符串列表中提取浮点数?

Python 如何仅从字符串列表中提取浮点数?,python,python-3.x,Python,Python 3.x,它没有按预期打印出[('candy',[1.3,1.23])],而是打印出: output = [] stuff = ['candy', '1.3', '1.23'] floats = map(float, stuff[1:]) tuples = (stuff[0], floats) output.append(tuples) print(output) [('candy',)] 我不知道出了什么问题,请告诉我解决方法。您的问题是没有将映射转换为列表,请尝试以下操作: [('candy',

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

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

我不知道出了什么问题,请告诉我解决方法。

您的问题是没有将
映射转换为列表,请尝试以下操作:

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


这是Python 2的地图评估:

>>> 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])]
>>> 
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对地图的懒惰评估:

>>> 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])]
>>> 
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]
Python 3.4.3(默认值,2015年6月10日19:56:14)
[GCC 4.2.1达尔文兼容苹果LLVM 6.1.0(clang-602.0.53)]
有关详细信息,请键入“帮助”、“版权”、“信用证”或“许可证”。
>>>地图(浮动,['1.1','1.2'])

您看到的是因为您正在Python3上运行代码。用
列表
换行以修复

在Python3
map
中,返回一个
map对象

这是在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>
输出:

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

它按照我的预期打印出了
[('candy',[1.3,1.23])]
。在python2和python3中,您的代码都可以工作。在py3中,它应该使用map objectdo
floats=list(map(float,stuff[1:])
,请参见