gpt4 book ai didi

python-3.x - Python __ror__ 和字典项上的其他二进制方法?

转载 作者:行者123 更新时间:2023-12-04 15:19:08 24 4
gpt4 key购买 nike

给定:

>>> 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)}

挠头

具有可交互性的字典 View 的二进制 的用例是什么? (或那里的其他二进制方法,__rxor____rand__ 也...)

最佳答案

稍微用力抓了一下,我发现我看到的是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

很有用!

关于python-3.x - Python __ror__ 和字典项上的其他二进制方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63717055/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com