【问题标题】:Python __ror__ and other binary methods on dict items?Python __ror__ 和 dict 项上的其他二进制方法?
【发布时间】:2020-12-22 07:16:28
【问题描述】:

给定:

>>> di1={'a':1,'b':2, 'c':3}

如果我这样做:

>>> dir(di1.items())
['__and__', '__class__', '__contains__', '__delattr__', 
 '__dir__', '__doc__', '__eq__', '__format__', '__ge__', 
 '__getattribute__', '__gt__', '__hash__', '__init__',    
 '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__',   
 '__ne__', '__new__', '__or__', '__rand__', '__reduce__',  
 '__reduce_ex__', '__repr__', '__reversed__', '__ror__', 
 '__rsub__', '__rxor__', '__setattr__', '__sizeof__', 
 '__str__', '__sub__', '__subclasshook__',
'__xor__', 'isdisjoint']

那里有一些有趣的方法。

试试__ror__

>>> help(di1.items())
...
 |  __ror__(self, value, /)
 |      Return value|self.
...

根据 Python 错误,value 只是一个可迭代对象。

让我们尝试一些例子:

>>> di1.items().__ror__([1])
{('c', 3), 1, ('b', 2), ('a', 1)}
>>> di1.items().__ror__([10])
{('c', 3), ('b', 2), 10, ('a', 1)}
>>> di1.items().__ror__([1000])
{1000, ('b', 2), ('c', 3), ('a', 1)}
>>> di1.items().__ror__([10,1000])
{('c', 3), ('a', 1), 1000, 10, ('b', 2)}

头疼

带有interable 的dict 视图的二进制or 的用例是什么? (或那里的其他二进制方法,__rxor____rand__ 也...)

【问题讨论】:

    标签: python-3.x dictionary binary


    【解决方案1】:

    在用力一点之后,我发现我正在查看的是dict view set operations 的一个元素,其中包括对.items() 的集合操作。

    给定:

    >>> di1={'a': 1, 'b': 2, 'c': 3}
    >>> di2={'a': 1, 'b': 3, 'c': 4, 'd':47, 'e':0}
    

    例子:

    >>> di1.items() & di2.items()
    {('a', 1)}
    # Only 'a' because with .items both key and value must be the same
    # equivalent to:
    # set(di1.items()) & set(di2.items())
    # However: values must be hashable
    
    >>> di1.keys() & ['a','d']
    {'a'}
    # only keys compared to a list
    # equivalent to set(di1.keys()) & set(['a', 'd'])
    
    # carefule tho: 
    # (di1.keys() | di2.keys()) & set(['a', 'e']) is right
    # di1.keys() | di2.keys() & set(['a', 'e']) is WRONG
    # since & is higher precedence than |
    
    
    >>> di1.keys() & 'zycd'
    {'c'}
    # and string
    # equivalent to  set(di1.keys()) & set('zycd')
    
    >>> di1.keys() | di2.keys()
    {'b', 'a', 'd', 'e', 'c'}
    # all the keys in both dicts -- since sets are used, not 
    # necessarily in order
    
    >>> di2.keys() - di1.keys()
    {'d', 'e'}
    # keys exclusively in di2
    

    有用的!

    【讨论】:

      猜你喜欢
      • 2015-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-30
      • 1970-01-01
      • 2020-11-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多