[英]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)
instead of printing out [('candy',[1.3,1.23])]
as intended, it prints out:它没有按预期打印出
[('candy',[1.3,1.23])]
,而是打印出:
[('candy', <map object at 0x00000000038AD940>)]
I don't know whats wrong please show me the fix.我不知道出了什么问题,请告诉我修复程序。
Your problem is that you aren't converting the map
to a list, try the following:您的问题是您没有将
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])]
>>>
In Python3 map
returns a map object
.在 Python3
map
返回一个map object
。
This is the way you can achieve what you want in Python3:这是你可以在 Python3 中实现你想要的方式:
floats = list(map(float, stuff[1:]))
The output:输出:
[('candy', [1.3, 1.23])]
This is Python 2 eval of map:这是地图的 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]
This is a Python3 lazy eval of 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>
What you are seeing is because you are running your code on Python 3. Wrap with list
to fix.你看到的是因为你在 Python 3 上运行你的代码。用
list
包裹来修复。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.