如何在Python中使用生成器表达式合并多个集合?

时间:2018-08-29 16:32:31

标签: python set

我想加入从一个类的实例获得的多个集合。以下是我正在使用的东西和尝试过的例子。更改类不是一种选择。

class Salad:
   def __init__(self, dressing, veggies, others):
      self.dressing = dressing
      self.veggies = veggies
      self.others = others

SALADS = {
   'cesar'  : Salad('cesar',  {'lettuce', 'tomato'},  {'chicken', 'cheese'}),
   'taco'   : Salad('salsa',  {'lettuce'},            {'cheese', 'chili', 'nachos'})
}

我希望OTHER_INGREDIENTS{'chicken', 'cheese', 'chili', 'nachos'}。所以我尝试了:

OTHER_INGREDIENTS = sum((salad.others for salad in SALADS.values()), set())

这给我一个错误:“ +不支持的操作数类型:'set'和'set'。我该怎么做?

如果可能的话,我宁愿使用不带其他导入功能的Python 2.7。

2 个答案:

答案 0 :(得分:2)

您可以使用设定的理解力:

OTHER_INGREDIENTS = {
    element
    for salad in SALADS.values()
    for element in salad.others
}

答案 1 :(得分:2)

您可以使用set中的函数联合:

OTHER_INGREDIENTS = set().union(*(salad.others for salad in SALADS.values()))

输出

{'chili', 'cheese', 'chicken', 'nachos'}