rwo*_*lst 2 python string floating-point list
例如,考虑Python中包含字母和数字字符串的列表
a = ['Total', '1', '4', '5', '2']
Run Code Online (Sandbox Code Playgroud)
如何将其转换为混合值列表
b = ['Total', 1.0, 4.0, 5.0, 2.0]
Run Code Online (Sandbox Code Playgroud)
请注意,通常我们可能不知道字母字符串在列表中的位置,即我们可能有的
a = ['Total', '1', '4', 'Next', '2']
Run Code Online (Sandbox Code Playgroud)
您可以使用生成器函数和异常处理:
>>> def func(seq):
for x in seq:
try:
yield float(x)
except ValueError:
yield x
...
>>> a = ['Total', '1', '4', '5', '2']
>>> list(func(a))
['Total', 1.0, 4.0, 5.0, 2.0]
Run Code Online (Sandbox Code Playgroud)