我有一个清单说:
['batting average', '306', 'ERA', '1710']
如何在不接触字符串的情况下转换预期的数字?
感谢您的帮助。
changed_list = [int(f) if f.isdigit() else f for f in original_list]
数据看起来就像你会知道数字应该在哪个位置。在这种情况下,最好在这些位置显式转换数据,而不是仅仅转换任何看起来像数字的东西:
ls = ['batting average', '306', 'ERA', '1710']
ls[1] = int(ls[1])
ls[3] = int(ls[3])
试试这个:
def convert( someList ):
for item in someList:
try:
yield int(item)
except ValueError:
yield item
newList= list( convert( oldList ) )
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 所指出的)