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

时间:2015-09-02 04:11:45

标签: python python-3.x

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>)]

我不知道什么是错的,请告诉我修复。

3 个答案:

答案 0 :(得分:1)

您的问题是您没有将.ca-icon转换为列表,请尝试以下操作:

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

答案 1 :(得分:1)

在Python3 map中返回map object

这是你在Python3中实现你想要的方式:

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

输出:

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

答案 2 :(得分:0)

这是地图的Python 2 eval:

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懒惰eval:

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进行修复。