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

问题描述 投票:0回答:2

我想加入从类实例中获取的多个集合。以下是我正在使用的内容和我尝试过的内容的示例。改变班级不是一种选择。

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而无需额外的导入。

python set
2个回答
2
投票

您可以使用set中的函数union:

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

产量

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

2
投票

您可以使用集合理解:

OTHER_INGREDIENTS = {
    element
    for salad in SALADS.values()
    for element in salad.others
}
© www.soinside.com 2019 - 2024. All rights reserved.