我有一个看起来像这样的列表:
['1', '2', '3.4', '5.6', '7.8']
Run Code Online (Sandbox Code Playgroud)
如何将前两个更改为int最后两个float?
我希望我的列表看起来像这样:
[1, 2, 3.4, 5.6, 7.8]
Run Code Online (Sandbox Code Playgroud)
Bha*_*Rao 12
>>> 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]
Run Code Online (Sandbox Code Playgroud)
有趣的指数边缘情况.您可以添加到条件.
>>> 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]
Run Code Online (Sandbox Code Playgroud)
使用isdigit是最好的,因为它处理所有边缘情况(史蒂文在评论中提到)
>>> 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]
Run Code Online (Sandbox Code Playgroud)
使用辅助函数:
def int_or_float(s):
try:
return int(s)
except ValueError:
return float(s)
Run Code Online (Sandbox Code Playgroud)
然后使用list comprehension来应用函数:
[int_or_float(el) for el in lst]
Run Code Online (Sandbox Code Playgroud)
为什么不用ast.literal_eval?
import ast
[ast.literal_eval(el) for el in lst]
Run Code Online (Sandbox Code Playgroud)
应该处理所有角落案件.对于这个用例来说,它有点重量级,但是如果你希望在列表中处理任何类似数字的字符串,那么这就行了.
| 归档时间: |
|
| 查看次数: |
5378 次 |
| 最近记录: |