列出理解,检查项目是否为uniqu

2024-06-07 00:33:12 发布

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

我试图写一个列表理解语句,它只会添加一个项目,如果它目前不包含在列表中。是否有方法检查当前正在构造的列表中的当前项?下面是一个简单的例子:

输入

{
    "Stefan" : ["running", "engineering", "dancing"],
    "Bob" : ["dancing", "art", "theatre"],
    "Julia" : ["running", "music", "art"]
}

输出

["running", "engineering", "dancing", "art", "theatre", "music"]

不使用列表理解的代码

output = []
for name, hobbies in input.items():
    for hobby in hobbies:
        if hobby not in output:
            output.append(hobby)

我的尝试

[hobby for name, hobbies in input.items() for hobby in hobbies if hobby not in ???]

Tags: namein列表forinputoutputmusicitems
3条回答

集合和字典是您的朋友:

from collections import OrderedDict
from itertools import chain # 'flattens' collection of iterables

data = {
    "Stefan" : ["running", "engineering", "dancing"],
    "Bob" : ["dancing", "art", "theatre"],
    "Julia" : ["running", "music", "art"]
}

# using set is the easiest way, but sets are unordered:
print {hobby for hobby in chain.from_iterable(data.values())}
# output:
# set(['art', 'theatre', 'dancing', 'engineering', 'running', 'music'])


# or use OrderedDict if you care about ordering:
print OrderedDict(
        (hobby, None) for hobby in chain.from_iterable(data.values())
    ).keys()
# output:
# ['dancing', 'art', 'theatre', 'running', 'engineering', 'music']

正如this answer所建议的:可以使用唯一性筛选器:

def f7(seq):
    seen = set()
    seen_add = seen.add
    return [x for x in seq if not (x in seen or seen_add(x))]

打电话给:

>>> f7(hobby for name, hobbies in input.items() for hobby in hobbies)
['running', 'engineering', 'dancing', 'art', 'theatre', 'music']

我将分别实现唯一性过滤器,因为设计规则说“不同的事情应该由不同的类/方法/组件/随便什么”。此外,如果需要,您可以简单地重用此方法。

另一个优点是——正如在linked answer中所写的那样——保留了项的顺序。对于某些应用程序,这可能是必要的。

您可以使用set并设置理解:

{hobby for name, hobbies in input.items() for hobby in hobbies}

作为m.wasowski mentioned,这里不使用name,因此可以使用item.values()

{hobby for hobbies in input.values() for hobby in hobbies}

如果您真的需要一个列表作为结果,您可以这样做(但请注意,通常您可以毫无问题地使用集合):

list({hobby for hobbies in input.values() for hobby in hobbies})

相关问题 更多 >