python - 将字符串列表转换为 int 或 float

标签 python list

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

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

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

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

[1, 2, 3.4, 5.6, 7.8]

最佳答案

使用 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]

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

>>> 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是最好的,因为它处理了所有边缘情况(由 Stevencomment 中提到)

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

关于python - 将字符串列表转换为 int 或 float,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33130279/

相关文章:

python - 使用Python按 block 解析文件并从每个 block 中提取信息

Python:如何将剩余的列表元素添加到列表中,类似于解压?

python - 使用 print (", ".join(my_array)) 提取单个字符串并将其添加到 Streamlit Markdown 中。我没有得到字符串,而是没有得到任何东西

python - 在 python 中,如何进行非阻塞系统调用?

list - Clojure 列表成员转换错误

list - 在 Scheme/Racket 中向左旋转列表

python - 如何对具有不同顺序的字符串列表进行排序?

python - Python 的根记录器的名称是什么?

python - 如何将整个文件读入python中的列表?

python - 声明的列表引发 NoneType 异常