如何将字符串列表中的整数转换为python中的整数?

如何将字符串列表中的整数转换为python中的整数?,python,Python,例如,我有一个字符串列表: lst = ["hello","ASKDJ","1","4","xcvs"] 如何将该字符串列表中的整数转换为整数?如果所有字符串字符都是数字,则有条件地将元素转换为整数。如果字符串的所有元素都是数字,则string方法返回true def convert(L): for i, elem in enumerate(L): if not elem.isdigit(): continue L[i] = in

例如,我有一个字符串列表:

lst = ["hello","ASKDJ","1","4","xcvs"]

如何将该字符串列表中的整数转换为整数?

如果所有字符串字符都是数字,则有条件地将元素转换为整数。如果字符串的所有元素都是数字,则string方法返回true

def convert(L):
    for i, elem in enumerate(L):
        if not elem.isdigit():
            continue
        L[i] = int(elem)

In [12]: L = ["hello","ASKDJ","1","4","xcvs"]

In [13]: convert(L)

In [14]: L
Out[14]: ['hello', 'ASKDJ', 1, 4, 'xcvs']
>>> [int(elem ) if elem.isdigit() else elem for elem in lst]
['hello', 'ASKDJ', 1, 4, 'xcvs']
使用方法和步骤:

伊斯迪吉特街

如果字符串中的所有字符都是数字,则返回true 至少有一个字符,否则为false


该列表中没有任何整数,只有字符串。可以使用int函数将一些字符串转换为整数

您将获得以下输出:

>>> 
Item hello cannot be turned into a number!
invalid literal for int() with base 10: 'hello'
Item ASKDJ cannot be turned into a number!
invalid literal for int() with base 10: 'ASKDJ'
Item xcvs cannot be turned into a number!
invalid literal for int() with base 10: 'xcvs'
现在请尝试打印列表:

>>> lst
['hello', 'ASKDJ', 1, 4, 'xcvs']

您真的需要为元素中的字符执行allchar.isdigit吗?《elem.isdigit》怎么了?@Abhijit:我不知道我能做到。谢谢:这样你甚至可以接受-12作为输入,因为它是一个有效的整数,即使它不包含唯一的数字。谢谢你的一个是最有用的。
>>> 
Item hello cannot be turned into a number!
invalid literal for int() with base 10: 'hello'
Item ASKDJ cannot be turned into a number!
invalid literal for int() with base 10: 'ASKDJ'
Item xcvs cannot be turned into a number!
invalid literal for int() with base 10: 'xcvs'
>>> lst
['hello', 'ASKDJ', 1, 4, 'xcvs']