从 python 上的字典获取集合运算符

get set operators from dict on python

如果我有两个或多个集合,并且有一个描述它们之间必须完成的de操作的字符串,比如'and'、'or'、'xor',显然可以像这样完成:

if string == 'and': 
    return set1.intersection(set2)
elif string == 'or'
    return set1 | set2

等等。如果我想用字典来做呢? 我有这样的东西:

dictionary = {'and': set.intersection, 'or': set.union}
return set1.dictionary[string](set2)

也尝试过

operation = dictionary.get(string)
return set1.operation(set2)

但是 none 有效。我怎样才能获得与通过 ifs 但使用字典相同的结果?

您可以使用set.itersection()set.union()等作为静态方法,将多个集合传递给它们:

>>> ops = {'and': set.intersection, 'or': set.union}
>>> set1 = {1, 2, 3}
>>> set2 = {3, 4, 5}
>>> ops['and'](set1, set2)
{3}
>>> ops['or'](set1, set2)
{1, 2, 3, 4, 5}

或者,您可以将操作映射到方法名称并使用 getattr():

>>> ops = {'and': 'intersection', 'or': 'union'}
>>> getattr(set1, ops['and'])(set2)
{3}
>>> getattr(set1, ops['or'])(set2)
{1, 2, 3, 4, 5}

你可以试试attrgetter

from operator import attrgetter

set_methods = {"and": attrgetter("intersection"), 'or': attrgetter("union")}

这样称呼它:set_methods[method_string](set1)(set2)