如果我有两个或两个以上的集合,并且有一个描述必须在它们之间完成的操作的字符串,例如“ 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)


但是没有一个有效。如何通过字典获得与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}

10-08 01:56