在列表中查找与列表不匹配的单词

2024-04-25 22:31:46 发布

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

希望在列表中查找与主列表中的单词不匹配的单词。你知道吗

代码为:

master = ['This', 'is', 'a', 'pond', 'full', 'of', 'good', 'words']
dontfindme = ['po', 'go', 'a']

预期结果是: ['This', 'is', 'full', 'of', 'words']

我们可以做:

list(set(master).difference(set([m for m in master for df in dontfindme if df in m])))

…但它搞砸了秩序。你知道吗

有没有更好的方法使用列表理解?你知道吗


Tags: of代码inmasterdf列表foris
2条回答
master = ['This', 'is', 'a', 'pond', 'full', 'of', 'good', 'words']
dontfindme = ['po', 'go', 'a']

result = [x for x in master if all(item not in x for item in dontfindme)]
print(result)

提供:

['This', 'is', 'full', 'of', 'words']

您可以使用^{}python内置方法。你知道吗

filter(function, iterable)

Construct an iterator from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.

Note that filter(function, iterable) is equivalent to the generator expression (item for item in iterable if function(item)) if function is not None and (item for item in iterable if item) if function is None.

def _filter():
    master = ['This', 'is', 'a', 'pond', 'full', 'of', 'good', 'words']
    dontfindme = ['po', 'go', 'a']

    return list(filter(lambda x: all([item not in x for item in dontfindme]), master))


if __name__ == '__main__':
    print(_filter())

输出:

['This', 'is', 'full', 'of', 'words']

相关问题 更多 >

    热门问题