简体   繁体   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)

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.

相关问题 从字符串列表中提取浮点数 - Extract floats from list of list of strings 如何将字符串列表列表转换为浮点数? - How do I turn a list of lists of lists of strings into floats? 从列表中仅提取整数(而不是浮点数) - Extract only the integers from list (not the floats) 如何从python列表中的元素中提取浮点数? - How do you extract the floats from the elements in a python list? 如何将由整数和浮点数组成的列表中的字符串列表转换为整数和浮点数? - How do I convert a list of strings in a list composed of ints and floats to both ints and floats? Python-如何从字符串列表中删除字母,将字符串更改为浮点数,转换一些浮点数并保持顺序 - Python - How can i remove a letter from a list of strings, change the strings to floats, transform some of the floats, and keep the order 如何仅从列表中提取第一个元素? - How do I extract only the first element from the list? 从字符串列表到浮点列表 - from list of strings into list of floats 如何从Python中的文件中提取浮点数? - How to I extract floats from a file in Python? 如何遍历字符串列表并识别整数和浮点数,然后将它们添加到列表中? - How do I iterate over a list of strings and identify ints and floats and then add them to a list?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM