TIM*_*ngs 12 python string integer numbers
我有一个清单说:
['batting average', '306', 'ERA', '1710']
Run Code Online (Sandbox Code Playgroud)
如何在不触及字符串的情况下转换预期的数字?
感谢您的帮助.
Ale*_*lli 41
changed_list = [int(f) if f.isdigit() else f for f in original_list]
Run Code Online (Sandbox Code Playgroud)
数据看起来像你应该知道数字应该在哪个位置.在这种情况下,最好显式转换这些位置的数据,而不是只转换看起来像数字的任何东西:
ls = ['batting average', '306', 'ERA', '1710']
ls[1] = int(ls[1])
ls[3] = int(ls[3])
Run Code Online (Sandbox Code Playgroud)
试试这个:
def convert( someList ):
for item in someList:
try:
yield int(item)
except ValueError:
yield item
newList= list( convert( oldList ) )
Run Code Online (Sandbox Code Playgroud)