如何从python中的列表中删除所有整数值

Jac*_*cky 9 python string

我只是python的初学者,我想知道是否可以从列表中删除所有整数值?例如,文件就像

['1','introduction','to','molecular','8','the','learning','module','5']
Run Code Online (Sandbox Code Playgroud)

删除后我希望文档看起来像:

['introduction','to','molecular','the','learning','module']
Run Code Online (Sandbox Code Playgroud)

Dan*_*ach 26

要删除所有整数,请执行以下操作:

no_integers = [x for x in mylist if not isinstance(x, int)]
Run Code Online (Sandbox Code Playgroud)

但是,您的示例列表实际上不包含整数.它只包含字符串,其中一些只由数字组成.要过滤掉这些,请执行以下操作:

no_integers = [x for x in mylist if not (x.isdigit() 
                                         or x[0] == '-' and x[1:].isdigit())]
Run Code Online (Sandbox Code Playgroud)

交替:

is_integer = lambda s: s.isdigit() or (x[0] == '-' and x[1:].isdigit())
no_integers = filter(is_integer, mylist)
Run Code Online (Sandbox Code Playgroud)


S.L*_*ott 13

你也可以这样做:

def int_filter( someList ):
    for v in someList:
        try:
            int(v)
            continue # Skip these
        except ValueError:
            yield v # Keep these

list( int_filter( items ))
Run Code Online (Sandbox Code Playgroud)

为什么?因为int比尝试编写规则或正则表达式来识别编码整数的字符串值更好.

  • 正如其他人指出的那样,`' - 2'.isdigit()`将返回'False`. (5认同)

Gar*_*err 11

列表中的所有项都不是整数.它们是仅包含数字的字符串.因此,您可以使用isdigit字符串方法过滤掉这些项目.

items = ['1','introduction','to','molecular','8','the','learning','module','5']

new_items = [item for item in items if not item.isdigit()]

print new_items
Run Code Online (Sandbox Code Playgroud)

链接到文档:http://docs.python.org/library/stdtypes.html#str.isdigit


twn*_*ale 5

我个人喜欢过滤器。我认为如果以明智的方式使用它可以帮助保持代码可读性和概念上的简单性:

x = ['1','introduction','to','molecular','8','the','learning','module','5'] 
x = filter(lambda i: not str.isdigit(i), x)
Run Code Online (Sandbox Code Playgroud)

或者

from itertools import ifilterfalse
x = ifilterfalse(str.isdigit, x)
Run Code Online (Sandbox Code Playgroud)

注意第二个返回一个迭代器。