Cha*_*n33 3 python string integer list
['10019', 'Airma25KLOS', 'Juridinis', 'LT', '121979631', 'LT219796314', '2410', '25', '26', '3232', '32131']
Run Code Online (Sandbox Code Playgroud)
在此列表中,每个项目都是一个字符串,我怎么能从该列表中得到相同顺序的相同列表,而不是现在是字符串的整数,如10019''121979631'等,以整数形式返回。
我的目标是使列表看起来像这样
[10019, 'Airma25KLOS', 'Juridinis', 'LT', 121979631, 'LZ219796314', 2410, 25, 26, 3232, 32131]
Run Code Online (Sandbox Code Playgroud)
如果字母和数字混合在一起,则应像LZ219796314'这样的字符串形式保留
对于任何可以有效表示整数(正数或负数)的字符串,该字符串都应适用。但这并不是说不能与浮点数一起使用。
def to_int(s):
try:
return int(s)
except (TypeError, ValueError) as e:
return s
result = [to_int(s) for s in your_list]
Run Code Online (Sandbox Code Playgroud)
您可以将以下列表理解与一起使用.isdigit,以便int仅转换为数字字符串:
l = ['10019', 'Airma25KLOS', 'Juridinis', 'LT', '121979631',
'LT219796314', '2410', '25', '26', '3232', '32131']
[int(i) if i.lstrip('-').isdigit() else i for i in l]
# [10019, 'Airma25KLOS', 'Juridinis', 'LT', 121979631, 'LT219796314',
# 2410, 25, 26, 3232, 32131]
Run Code Online (Sandbox Code Playgroud)