如何在Python中将元组的第二个元素从字符串转换为浮点数?

huangapple go评论64阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年4月17日 01:11:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76029235.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定