将字符串列表转换为int或float [英] Convert a list of strings to either int or float

查看:129
本文介绍了将字符串列表转换为int或float的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的列表:

I have a list which looks something like this:

['1', '2', '3.4', '5.6', '7.8']

如何将前两个更改为int,最后三个更改为float?

How do I change the first two to int and the three last to float?

我希望我的列表看起来像这样:

I want my list to look like this:

[1, 2, 3.4, 5.6, 7.8]

推荐答案

在列表理解中使用有条件的

Use a conditional inside a list comprehension

>>> s = ['1', '2', '3.4', '5.6', '7.8']
>>> [float(i) if '.' in i else int(i) for i in s]
[1, 2, 3.4, 5.6, 7.8]

有趣的指数边缘情况.您可以添加到条件中.

Interesting edge case of exponentials. You can add onto the conditional.

>>> s = ['1', '2', '3.4', '5.6', '7.8' , '1e2']
>>> [float(i) if '.' in i or 'e' in i else int(i) for i in s]
[1, 2, 3.4, 5.6, 7.8, 100.0]

使用 isdigit 是最好的选择会处理所有边缘情况(由 Steven 提到. com/questions/33130279/convert-a-of-strings-to-int-and-float/33130297?noredirect = 1#comment54072755_33130297>评论)

Using isdigit is the best as it takes care of all the edge cases (mentioned by Steven in a comment)

>>> s = ['1', '2', '3.4', '5.6', '7.8']
>>> [int(i) if i.isdigit() else float(i) for i in s]
[1, 2, 3.4, 5.6, 7.8, 100.0]

这篇关于将字符串列表转换为int或float的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆