我想加入从一个类的实例获得的多个集合。以下是我正在使用的东西和尝试过的例子。更改类不是一种选择。
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。
答案 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'}