将Python的字符串列表转换为浮点数,其中列表还包含单词 [英] Convert Python list of strings into floats, where list also contains words

查看:356
本文介绍了将Python的字符串列表转换为浮点数,其中列表还包含单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,考虑Python中包含字母和数字字符串的列表

  a = ['Total','1 ','4','5','2'] 

如何转换这到混合值列表

$ $ p $ $ $ c $ b = ['Total',1.0,4.0,5.0,2.0]

请注意,一般来说,我们可能不知道字符串在列表中的位置,即可能有

  a = ['Total','1','4','Next','2'] 
$解析方案您可以使用一个生成器函数和异常处理:

 >>> def func(seq):
for x in seq:
try:
yield float(x)
除ValueError:
yield x
...
>>> a = ['Total','1','4','5','2']
>>> list(func(a))
['Total',1.0,4.0,5.0,2.0]


Consider for example the list in Python containing both strings of letters and numbers

a = ['Total', '1', '4', '5', '2']

How would it be possible to convert this into the mixed value list

b = ['Total', 1.0, 4.0, 5.0, 2.0]

Note that in general we may not know where the letters string will be in the list i.e. we might have

a = ['Total', '1', '4', 'Next', '2']

解决方案

You can use a generator function and exception handling:

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

这篇关于将Python的字符串列表转换为浮点数,其中列表还包含单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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