Python 如果找不到则删除

Python Remove if Not Found

下面的代码有效,但我对是否有 shorter/more elegant/more "Pythonic" 编程以下内容的方法感兴趣:

#!/usr/bin/env python

from sortedcontainers import SortedSet

def removeSubsumed(L, R):
    """Returns those lists in L that are not supersets of any list in R"""
    result = []
    for l in L:
        fg = True
        for r in R:
            if l >= r:
                fg = False
                break
        if fg:
            result.append(l)
    return result

print removeSubsumed([ SortedSet([ 'a', 'b', 'c' ]),
                       SortedSet([ 'd', 'e', 'f' ]),
                       SortedSet([ 'g', 'h', 'i' ]) ],
                     [ SortedSet([ 'a', 'b' ]),
                       SortedSet([ 'g' ]) ])

您可以使用 any() 和列表理解 。示例 -

def removeSubsumed(L, R):
    return [s for s in L if not any(s >= r for r in R)]

any() - Return 如果任何元素为真则为真,否则 returns 为假(即使它作为参数接收的可迭代对象为空)。

您也可以尝试功能性方法,但我不得不说, 方法工作得更快:

def removeSubsumed(L, R):
    return filter(lambda l: not any(map(lambda r: l >= r, R)), L)

print(list(removeSubsumed(...)))