【问题标题】:Remove list entries containing multiple conditions删除包含多个条件的列表条目
【发布时间】:2018-12-10 22:46:54
【问题描述】:

我有字符串形式的路径列表

>>> p = ['/path/one/foo.txt', '/path/two/foo.txt', '/path/three/foo.txt', '/path/four/foo.txt]

我知道我可以使用类似的方法从列表中删除包含单词的条目

>>> p = [x for x in p if 'two' not in x]

>>> p

['/path/one/foo.txt', '/path/three/foo.txt', '/path/four/foo.txt']

但是,这似乎不起作用

>>> p = [x for x in p if 'two' or 'three' not in x]

>>> p

['/path/one/foo.txt', '/path/two/foo.txt', '/path/three/foo.txt', '/path/four/foo.txt]`

如何删除p 中包含twothree 的所有条目?

注意,我是从 dict 中的不同键中提取值 twothree,因此创建单个列表可能并不简单。

【问题讨论】:

    标签: python string python-2.7 list filepath


    【解决方案1】:

    试试这个:

    p = [x for x in p if 'two' not in x and 'three' not in x]
    

    【讨论】:

    • 这似乎是票
    • 是的,只是做一些测试
    【解决方案2】:

    您可以将all 与生成器表达式一起使用:

    values = ('two', 'three')
    p = [x for x in p if all(i not in x for i in values)]
    

    更好的办法是提取特定文件夹并将其与set 进行比较。您的示例很简单,因为您只对第二个目录感兴趣:

    values = {'two', 'three'}
    
    L = ['/path/one/foo.txt', '/path/two/foo.txt',
         '/path/three/foo.txt', '/path/four/foo.txt']
    
    res = [i for i in L if i.split('/')[2] not in values]
    
    print(res)
    
    ['/path/one/foo.txt', '/path/four/foo.txt']
    

    【讨论】:

      【解决方案3】:

      使用正则表达式。 --> re.search(r"(two|three)", x)

      演示:

      import re
      p = ['/path/one/foo.txt', '/path/two/foo.txt', '/path/three/foo.txt', '/path/four/foo.txt']
      p = [x for x in p if not re.search(r"(two|three)", x)]
      print(p)
      

      输出:

      ['/path/one/foo.txt', '/path/four/foo.txt']
      

      【讨论】:

        【解决方案4】:

        p = [x for x in p if 'two' not in x and 'three' not in x]

        在 Python 中,您有两个独立的布尔语句:'two' in x'three' in x。您使用的语法不起作用,因为 Python 无法将该语法识别为两个单独的布尔语句。

        【讨论】:

        • 这很有帮助,但根据Ayoub Laazazi,我认为我应该使用and 而不是or
        • 是的,你是对的。我编辑了我的帖子以反映这一点。
        【解决方案5】:

        @afg1997,您也可以继续使用自己的方法,只需将 or 替换为 and 并在代码中稍作修改即可跟随。

        >>> p = ['/path/one/foo.txt', '/path/two/foo.txt', '/path/three/foo.txt', '/path/four/foo.txt']
        >>>
        >>> [x for x in p if not 'two' in x and not 'three' in x]
        ['/path/one/foo.txt', '/path/four/foo.txt']
        >>>
        

        【讨论】:

          猜你喜欢
          • 2014-09-11
          • 2011-09-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多