[英]How to merge multiple sets in Python with a generator expression?
I want to join multiple sets that are obtained from instances of a class. 我想加入从一个类的实例获得的多个集合。 Below is an example of what I am working with and what I tried.
以下是我正在使用的东西和尝试过的例子。 Changing the class is not an option.
更改类不是一种选择。
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'})
}
I want OTHER_INGREDIENTS
to be {'chicken', 'cheese', 'chili', 'nachos'}
. 我希望
OTHER_INGREDIENTS
为{'chicken', 'cheese', 'chili', 'nachos'}
。 So I tried: 所以我尝试了:
OTHER_INGREDIENTS = sum((salad.others for salad in SALADS.values()), set())
That gives me an error "unsupported operand type(s) for +: 'set' and 'set' though. How do I do this? 那给我一个错误“ +不支持的操作数类型:'set'和'set'。我该怎么做?
I would prefer to use Python 2.7 without additional imports if possible. 如果可能的话,我宁愿使用不带其他导入功能的Python 2.7。
You can use a set comprehension: 您可以使用集合理解:
OTHER_INGREDIENTS = {
element
for salad in SALADS.values()
for element in salad.others
}
You can use the function union from set: 您可以使用set中的函数并集:
OTHER_INGREDIENTS = set().union(*(salad.others for salad in SALADS.values()))
Output 产量
{'chili', 'cheese', 'chicken', 'nachos'}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.