英文:
How to convert the second element of a tuple from string to float in Python?
问题
I'm learning Python and I have extracted this out of a .txt
file using split(";")
:
[(86246, '7.5'), (86246, '1.5'), (86246, '5.9'), (86246, '1.9'), (86246, '10.3'), (86246, '7.')]
I would like to get the following result:
[(86246, 7.5), (86246, 1.5), (86246, 5.9), (86246, 1.9), (86246, 10.3), (86246, 7.)]
The goal is to obtain float values rather than strings to then make a dictionary out of this method.
英文:
I'm learning Python and I have extracted this out of a .txt
file using split(";")
:
[(86246, '7.5'), (86246, '1.5'), (86246, '5.9'), (86246, '1.9'), (86246, '10.3'), (86246, '7.')]
I would like to get the following result:
[(86246, 7.5), (86246, 1.5), (86246, 5.9), (86246, 1.9), (86246, 10.3), (86246, 7.)]
The goal is to obtain float values rather than strings to then make a dictionary out of this method.
答案1
得分: 2
你可以尝试使用list comprehensions:
>>> 列表 = [(86246, '7.5'), (86246, '1.5'), (86246, '5.9'), (86246, '1.9'), (86246, '10.3'), (86246, '7.')]
>>> [(t[0], float(t[1])) for t in 列表]
[(86246, 7.5), (86246, 1.5), (86246, 5.9), (86246, 1.9), (86246, 10.3), (86246, 7.0)]
英文:
You could try using list comprehensions:
>>> list = [(86246, '7.5'), (86246, '1.5'), (86246, '5.9'), (86246, '1.9'), (86246, '10.3'), (86246, '7.')]
>>> [(t[0], float(t[1])) for t in list]
[(86246, 7.5), (86246, 1.5), (86246, 5.9), (86246, 1.9), (86246, 10.3), (86246, 7.0)]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论