Python检查列表项是否为整数?

2024-04-19 08:55:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个列表,其中包含字符串格式的数字和字母

mylist=['1','orange','2','3','4','apple']

我需要列出一个新的列表,其中只包含数字:

mynewlist=['1','2','3','4']

如果我有办法检查列表中的每个项目是否可以转换为整数,我应该能够通过如下操作得出我想要的结果:

for item in mylist:
    if (check item can be converted to integer):
        mynewlist.append(item)

如何检查字符串是否可以转换为整数?还是有更好的方法


Tags: 项目字符串inapple列表for格式字母
3条回答

您可以使用异常处理,因为str.digit只适用于整数,并且也可能会在类似情况下失败:

>>> str.isdigit(' 1')
False

使用生成器功能:

def solve(lis):                                        
    for x in lis:
        try:
            yield float(x)
        except ValueError:    
            pass

>>> mylist = ['1','orange','2','3','4','apple', '1.5', '2.6']
>>> list(solve(mylist))                                    
[1.0, 2.0, 3.0, 4.0, 1.5, 2.6]   #returns converted values

或者你想要这个:

def solve(lis):
    for x in lis:
        try:
            float(x)
            return True
        except:
            return False
...         
>>> mylist = ['1','orange','2','3','4','apple', '1.5', '2.6']
>>> [x for x in mylist if solve(x)]
['1', '2', '3', '4', '1.5', '2.6']

或者使用ast.literal_eval,这将适用于所有类型的数字:

>>> from ast import literal_eval
>>> def solve(lis):
    for x in lis:
        try:
            literal_eval(x)
            return True
        except ValueError:   
             return False
...         
>>> mylist=['1','orange','2','3','4','apple', '1.5', '2.6', '1+0j']
>>> [x for x in mylist if solve(x)]                               
['1', '2', '3', '4', '1.5', '2.6', '1+0j']

试试这个:

mynewlist = [s for s in mylist if s.isdigit()]

docs开始:

str.isdigit()

Return true if all characters in the string are digits and there is at least one character, false otherwise.

For 8-bit strings, this method is locale-dependent.


如注释中所述,isdigit()返回的True不一定表示可以通过int()函数将字符串解析为int,返回的False不一定表示不能解析。然而,上述方法应该适用于您的情况

快速、简单,但可能并不总是正确的:

>>> [x for x in mylist if x.isdigit()]
['1', '2', '3', '4']

如果您需要获取数字,请使用更传统的方式:

new_list = []
for value in mylist:
    try:
        new_list.append(int(value))
    except ValueError:
        continue

注意:结果包含整数。如果需要,将它们转换回字符串, 将上面的行替换为:

try:
    new_list.append(str(int(value)))

相关问题 更多 >