gpt4 book ai didi

python - 当存在重复项时查找列表之间的差异

转载 作者:行者123 更新时间:2023-12-01 00:36:33 26 4
gpt4 key购买 nike

我需要使用 python 找出两个列表之间的差异。这个问题之前在 Stack Overflow 上已经被问过很多次了,但没有一个提到重复(即 [8][8, 0, 1, 8] 之间的区别)是 [0, 1];我需要它是 [0, 1, 8],因为每个数字在我的程序中都很重要)。

我尝试过使用numpy的setdiff1d,但它无法满足上述条件

ydiff = np.setdiff1d(ydigits, jdigits)

如上所述,这仅考虑相同的项目是否在列表中,而不考虑它在该列表中出现的次数。还有其他我可以使用的功能吗?

最佳答案

您可以使用 collections.Counter 的减法运算符对象代替:

>>> from collections import Counter
>>> list((Counter([8, 0, 1, 8]) - Counter([8])).elements())
[8, 0, 1]

关于python - 当存在重复项时查找列表之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57715120/

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