如果您在项目中选择 Python2.7。在这种情况下可以使用Counter():
Python 2.7.16 (default, Jun 5 2020, 22:59:21)
[GCC 4.2.1 Compatible Apple LLVM 11.0.3 (clang-1103.0.29.20) (-macos10.15-objc- on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> x={1:['a','b','c']}
>>> y={1:['d','e','f'],2:['g']}
>>> from collections import Counter
>>> Counter(x) + Counter(y)
Counter({2: ['g'], 1: ['a', 'b', 'c', 'd', 'e', 'f']})
在 Python 3.x 中,如果你运行相同的代码,你会看到:
Python 3.9.0 (v3.9.0:9cf6752276, Oct 5 2020, 11:29:23)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.19.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: x={1:['a','b','c']}
In [2]: y={1:['d','e','f'],2:['g']}
In [3]: from collections import Counter
In [4]: Counter(x) + Counter(y)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-0aa8b00837b3> in <module>
----> 1 Counter(x) + Counter(y)
/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/collections/__init__.py in __add__(self, other)
759 for elem, count in self.items():
760 newcount = count + other[elem]
--> 761 if newcount > 0:
762 result[elem] = newcount
763 for elem, count in other.items():
TypeError: '>' not supported between instances of 'list' and 'int'
我们看一下vim /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/collections/__init__.py +761的源码
为了检查Python2.x和Python3.x之间的区别,我们将在python2中找到集合的路径。要做到这一点,只需执行一个错误的调用,例如:
>>> Counter(9,1) # wrong way to call.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/collections.py", line 475, in __init__
raise TypeError('expected at most 1 arguments, got %d' % len(args))
TypeError: expected at most 1 arguments, got 2
然后,您会看到/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/collections.py。
好的,现在打开这两个文件并定位到class Counter 中的__add__ 函数。
vim -d /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/collections/__init__.py +761 /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/collections.py
但我们可以在这个狙击代码中找到相应的。
想想这个,你可以看到TypeError: '>' not supported between instances of 'list' and 'int'显示了两个重要的东西:
-
>
反映到class dict 中的def __gt__(self, value, /) 方法。那么让我们来看看python2和python3dict之间的区别。
-
'list' 和 'int'。为了确保我们在这里遇到相同的类型,只需添加一行即可将其打印出来。在这样做之前比较行 if newcount > 0: 像这样:
print("newcount is --> ", newcount, type(newcount))
if newcount > 0:
你会看到这个:
并不奇怪,对吧?我们可以将list 与int 进行比较,这很有意义..
让我们在 python 2 中快速比较 list 和 int。
它返回一个True。继续深入Python3.x
好的,现在您应该清楚发生了什么。要解决这个问题,应该很容易地对您自己的 python 环境进行一些更改或将其提交给git。
最后,您有两个好消息,您修复了 Python3.x 错误。你得到了你的结果。
如果想要的结果是一个字典。您可以使用以下内容:
z = dict(Counter(x) + Counter(y))