【问题标题】:How to remove all integer values from a list in python如何从python中的列表中删除所有整数值
【发布时间】:2011-03-10 16:54:58
【问题描述】:

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

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

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

['introduction','to','molecular','the','learning','module']

【问题讨论】:

    标签: python string


    【解决方案1】:

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

    no_integers = [x for x in mylist if not isinstance(x, int)]
    

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

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

    交替:

    is_integer = lambda s: s.isdigit() or (s[0] == '-' and s[1:].isdigit())
    no_integers = filter(is_integer, mylist)
    

    【讨论】:

    • 如果你想就地修改列表而不是创建列表,这可以通过简单的循环来完成。
    • @mykhal 只是检查一下,这是在开玩笑吗?当然,它确实适用于多位数字
    • @razpetia:已修复以处理负数
    • 泛化使这一点变得不那么清楚。请改用 S. Lott 的 Pythonic 答案。
    • @Daniel Stutzbach:您的过滤功能很棒,但您应该使用 filter()。保持pythonic,你知道..
    【解决方案2】:

    你也可以这样做:

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

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

    【讨论】:

    • 为什么intstr.isdigit 更好?
    • 正如其他人指出的那样,'-2'.isdigit() 将返回False
    • +1。请参阅stackoverflow.com/questions/354038/… 进行讨论(与float,但仍然同样相关)。
    【解决方案3】:

    列表中的所有项目都不是整数。它们是只包含数字的字符串。所以你可以使用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
    

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

    【讨论】:

      【解决方案4】:

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

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

      from itertools import ifilterfalse
      x = ifilterfalse(str.isdigit, x)
      

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

      【讨论】:

        【解决方案5】:

        请不要使用这种方式从列表中删除项目:(由 THC4k 评论后编辑)

        >>> li = ['1','introduction','to','molecular','8','the','learning','module','5']
        >>> for item in li:
                if item.isdigit():
                    li.remove(item)
        
        >>> print li
        ['introduction', 'to', 'molecular', 'the', 'learning', 'module']
        

        这不起作用,因为在迭代列表时更改列表会混淆 for 循环。 此外,如 razpeitia 所述,如果 item 是包含负整数的字符串,item.isdigit() 将不起作用。

        【讨论】:

        • Python 确实需要一种机制来防止人们这样做。看起来它会起作用,但它不起作用 - 尝试使用 li = ['iterating + removing -> skipping', '4', '5', 'see?'](删除 4 将跳过 5,因此它保留在列表中)
        【解决方案6】:

        您还可以使用 lambdas(显然还有递归)来实现(需要 Python 3):

         isNumber = lambda s: False if ( not( s[0].isdigit() ) and s[0]!='+' and s[0]!='-' ) else isNumberBody( s[ 1:] )
        
         isNumberBody = lambda s: True if len( s ) == 0 else ( False if ( not( s[0].isdigit() ) and s[0]!='.' ) else isNumberBody( s[ 1:] ) )
        
         removeNumbers = lambda s: [] if len( s ) == 0 else ( ( [s[0]] + removeNumbers(s[1:]) ) if ( not( isInteger( s[0] ) ) ) else [] + removeNumbers( s[ 1:] ) )
        
         l = removeNumbers(["hello", "-1", "2", "world", "+23.45"])
         print( l )
        

        结果(从 'l' 显示)将是:['hello', 'world']

        【讨论】:

        • 嗯,是的,但是更改该代码以实现该行为将是微不足道的。
        • 完成,现在它可以处理负数了。
        【解决方案7】:

        从列表中删除所有整数

        ls = ['1','introduction','to','molecular','8','the','learning','module','5']
        ls_alpha = [i for i in ls if not i.isdigit()]
        print(ls_alpha)
        

        【讨论】:

          【解决方案8】:

          您可以使用内置的filter 来获取列表的过滤副本。

          >>> the_list = ['1','introduction','to','molecular',-8,'the','learning','module',5L]
          >>> the_list = filter(lambda s: not str(s).lstrip('-').isdigit(), the_list)
          >>> the_list
          ['introduction', 'to', 'molecular', 'the', 'learning', 'module']
          

          上面可以通过使用显式类型转换来处理各种对象。由于几乎每个 Python 对象都可以合法地转换为字符串,因此filter 为 the_list 的每个成员获取一个经过 str 转换的副本,并检查字符串(减去任何前导“-”字符)是否为数字。如果是,则从返回的副本中排除该成员。

          The built-in functions are very useful. 它们每个都针对它们旨在处理的任务进行了高度优化,它们将使您免于重新发明解决方案。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2017-05-07
            • 2018-06-17
            • 2015-04-03
            • 2016-08-26
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多