Common elements between two lists not using sets in Python(两个列表之间的公共元素不使用 Python 中的集合)
问题描述
我想计算两个列表的相同元素.列表可以有重复的元素,所以我不能将它转换为集合并使用 &运算符.
I want count the same elements of two lists. Lists can have duplicate elements, so I can't convert this to sets and use & operator.
a=[2,2,1,1]
b=[1,1,3,3]
set(a) &设置(b)工作
一个&b 不工作
set(a) & set(b) work
a & b don't work
没有set和dictionary也可以吗?
It is possible to do it withoud set and dictonary?
推荐答案
在 Python 3.x(和 Python 2.7,当它发布时),你可以使用 collections.Counter 为此:
In Python 3.x (and Python 2.7, when it's released), you can use collections.Counter for this:
>>> from collections import Counter
>>> list((Counter([2,2,1,1]) & Counter([1,3,3,1])).elements())
[1, 1]
这是使用 collections.defaultdict 的替代方法(在 Python 2.5 中可用然后).它有一个很好的属性,即结果的顺序是确定的(它本质上对应于第二个列表的顺序).
Here's an alternative using collections.defaultdict (available in Python 2.5 and later). It has the nice property that the order of the result is deterministic (it essentially corresponds to the order of the second list).
from collections import defaultdict
def list_intersection(list1, list2):
bag = defaultdict(int)
for elt in list1:
bag[elt] += 1
result = []
for elt in list2:
if elt in bag:
# remove elt from bag, making sure
# that bag counts are kept positive
if bag[elt] == 1:
del bag[elt]
else:
bag[elt] -= 1
result.append(elt)
return result
对于这两种解决方案,输出列表中任何给定元素 x 的出现次数是两个输入列表中 x 出现次数的最小值.从您的问题中不清楚这是否是您想要的行为.
For both these solutions, the number of occurrences of any given element x in the output list is the minimum of the numbers of occurrences of x in the two input lists. It's not clear from your question whether this is the behavior that you want.
这篇关于两个列表之间的公共元素不使用 Python 中的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:两个列表之间的公共元素不使用 Python 中的集合
基础教程推荐
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 包装空间模型 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
