【问题标题】:get set operators from dict on python从python上的dict获取集合运算符
【发布时间】:2018-09-16 20:12:02
【问题描述】:

如果我有两个或更多集合,以及一个描述必须在它们之间完成的 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)

但没有一个有效。我怎样才能获得与 ifs 相同但使用字典的结果?

【问题讨论】:

    标签: python dictionary set logical-operators


    【解决方案1】:

    您可以使用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}
    

    【讨论】:

    • 没错。如果我还必须有 set.difference 运算符怎么办?那么它需要两个参数,但它们不能互换。
    • 你能澄清一下吗?如果您以相同的顺序传递集合,那么set.difference 也应该可以工作。您还可以在集合对象上使用gettatr()(请参阅更新)。
    • 你是对的。我很困惑,因为直接实现,方法是写set1.difference(set2)0所以我认为set.difference(set1, set2)会像set() - set1 - set2
    【解决方案2】:

    你可以试试attrgetter

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-10
      • 2022-01-24
      • 1970-01-01
      • 2023-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多