Python 返回字符串列表中包含整数和字符串的列表
在这个列表中,每个项目都是一个字符串,我如何从这个列表中,以相同的顺序创建相同的列表,而不是像10019''121979631'等现在是字符串的整数,以整数的形式返回 我的目标是让列表看起来像这样Python 返回字符串列表中包含整数和字符串的列表,python,string,list,integer,Python,String,List,Integer,在这个列表中,每个项目都是一个字符串,我如何从这个列表中,以相同的顺序创建相同的列表,而不是像10019''121979631'等现在是字符串的整数,以整数的形式返回 我的目标是让列表看起来像这样 ['10019', 'Airma25KLOS', 'Juridinis', 'LT', '121979631', 'LT219796314', '2410', '25', '26', '3232', '32131'] 如果字母和数字混合在一起,则应保持为类似LZ219796314'的字符串。您可以使
['10019', 'Airma25KLOS', 'Juridinis', 'LT', '121979631', 'LT219796314', '2410', '25', '26', '3232', '32131']
如果字母和数字混合在一起,则应保持为类似LZ219796314'的字符串。您可以使用以下列表,以便仅转换为
int
数字字符串:
[10019, 'Airma25KLOS', 'Juridinis', 'LT', 121979631, 'LZ219796314', 2410, 25, 26, 3232, 32131]
这应该适用于任何整数的有效表示形式的字符串(无论是正的还是负的)。不过,如果不能与浮动一起使用,则不是这样
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]
使用此代码。它适用于负整数以及浮点等情况 代码:
def to_int(s):
try:
return int(s)
except (TypeError, ValueError) as e:
return s
result = [to_int(s) for s in your_list]
def is_number(s):
try:
float(s)
return True
except ValueError:
pass
try:
import unicodedata
unicodedata.numeric(s)
return True
except (TypeError, ValueError):
pass
return False
l = ['10019', 'Airma25KLOS', 'Juridinis', 'LT', '121979631',
'LT219796314', '2410', '-25', '26', '3232', '32131']
print([int(i) if is_number(i) else i for i in l])
输出:
def to_int(s):
try:
return int(s)
except (TypeError, ValueError) as e:
return s
result = [to_int(s) for s in your_list]
def is_number(s):
try:
float(s)
return True
except ValueError:
pass
try:
import unicodedata
unicodedata.numeric(s)
return True
except (TypeError, ValueError):
pass
return False
l = ['10019', 'Airma25KLOS', 'Juridinis', 'LT', '121979631',
'LT219796314', '2410', '-25', '26', '3232', '32131']
print([int(i) if is_number(i) else i for i in l])
你可以试试这个:
[10019, 'Airma25KLOS', 'Juridinis', 'LT', 121979631, 'LT219796314', 2410, -25, 26, 3232, 32131]
我不确定这是否是最好的方法,但这适用于所有整数(正整数和负整数)您可以使用正则表达式检查字符串是否为整数:
l=['-10019', 'Airma25KLOS', 'Juridinis', 'LT', '121979631', 'LT219796314', '2410', '25', '26', '3232', '32131']
a=[]
for item in l:
try:
a.append(int(item))
except:
a.append(item)
不太健壮。如果其中一个整数是负数呢?@JohnColeman是对的。在我看来,一个更严格的方法是定义一个单独的函数,以便对字符串是否为整数进行更可靠的检查。@JohnColeman很好。将添加考虑负整数的更新also@yatu这取决于预期用途。对于以10为基数的正整数文本(OP似乎已经考虑到了这一点),这很好。OP当然应该知道
isdigit()
,但也应该知道它的局限性。这种方法只适用于整数,以及其他建议的解决方案。对于+符号,您可以简单地用-和+,i.lstrip(“+-”)
@MykolaZotkoYep左撇,这就是我的想法+1behtreen hogaya!:)舒克里亚:)@DirtyBit