12

我有一个清单说:

['batting average', '306', 'ERA', '1710']

如何在不接触字符串的情况下转换预期的数字?

感谢您的帮助。

4

4 回答 4

41
changed_list = [int(f) if f.isdigit() else f for f in original_list]
于 2009-05-04T06:11:33.267 回答
5

数据看起来就像你会知道数字应该在哪个位置。在这种情况下,最好在这些位置显式转换数据,而不是仅仅转换任何看起来像数字的东西:

ls = ['batting average', '306', 'ERA', '1710']
ls[1] = int(ls[1])
ls[3] = int(ls[3])
于 2009-05-04T06:18:20.660 回答
5

试试这个:

def convert( someList ):
    for item in someList:
        try:
            yield int(item)
        except ValueError:
            yield item

newList= list( convert( oldList ) )
于 2009-05-04T10:40:37.503 回答
0
a= ['batting average', '306', 'ERA', '1710.5']

[f if sum([c.isalpha() for c in f]) else float(f) for f in a ]

如果您的列表包含浮点数、字符串和整数(正如评论中@d.putto 所指出的)

于 2015-04-24T14:50:06.920 回答