找到 2 列表之间的非交集,包括重复
find the non intersection between 2 list, including duplicate
问这个问题之前我试着查了一下,但没有找到令人满意的。所以我有 2 个这样的列表
a=[1,2,3,4,4]
b=[1,1,2,3,4]
我试过这个:
set(a) - set(b)
但是得到了这个
set()
我要的是这个
[1,4]
因为集合 a 有 2 个 4,集合 b 有 2 个 1。我能做什么?谢谢!
使用 collections.Counter
对象比较各个值的出现次数:
from collections import Counter
a = [1, 2, 3, 4, 4]
b = [1, 1, 2, 3, 4]
a_counts, b_counts = Counter(a), Counter(b)
res = [a_key for a_key, b_key in zip(a_counts, b_counts)
if a_counts[a_key] != b_counts[b_key]]
print(res) # [1, 4]
使用collections.Counter, is the Python implementation of a multiset:
from collections import Counter
a = [1, 2, 3, 4, 4]
b = [1, 1, 2, 3, 4]
c = [1, 1, 1, 2, 3, 4]
counts_a = Counter(a)
counts_b = Counter(b)
counts_c = Counter(c)
result_b = (counts_a | counts_b) - (counts_a & counts_b)
result_c = (counts_a | counts_c) - (counts_a & counts_c)
print(list(result_b.elements()))
print(list(result_c.elements()))
输出
[1, 4]
[1, 1, 4]
请注意 (counts_a | counts_b) - (counts_a & counts_b)
是数学公式的 Python 等价物。
问这个问题之前我试着查了一下,但没有找到令人满意的。所以我有 2 个这样的列表
a=[1,2,3,4,4]
b=[1,1,2,3,4]
我试过这个:
set(a) - set(b)
但是得到了这个
set()
我要的是这个
[1,4]
因为集合 a 有 2 个 4,集合 b 有 2 个 1。我能做什么?谢谢!
使用 collections.Counter
对象比较各个值的出现次数:
from collections import Counter
a = [1, 2, 3, 4, 4]
b = [1, 1, 2, 3, 4]
a_counts, b_counts = Counter(a), Counter(b)
res = [a_key for a_key, b_key in zip(a_counts, b_counts)
if a_counts[a_key] != b_counts[b_key]]
print(res) # [1, 4]
使用collections.Counter, is the Python implementation of a multiset:
from collections import Counter
a = [1, 2, 3, 4, 4]
b = [1, 1, 2, 3, 4]
c = [1, 1, 1, 2, 3, 4]
counts_a = Counter(a)
counts_b = Counter(b)
counts_c = Counter(c)
result_b = (counts_a | counts_b) - (counts_a & counts_b)
result_c = (counts_a | counts_c) - (counts_a & counts_c)
print(list(result_b.elements()))
print(list(result_c.elements()))
输出
[1, 4]
[1, 1, 4]
请注意 (counts_a | counts_b) - (counts_a & counts_b)
是数学公式的 Python 等价物。