两个列表的共同元素包括重复
Common elements of two lists including repetitions
我有两个列表:
a = ['item.1','item.2','item.3', 'another_item']
b = ['item.4','item.5', 'another_item']
我将拆分元素以结束
a = ['item', 'item', 'item', 'another_item']
b = ['item', 'item', 'another_item']
我想找到实际的共享项目,最后得到
c = ['item','item', 'another_item']
但是set(a).intersection(b)
会return我['item', 'another_item']
和
c = [x for x in list1 if x in list2]
returns ['item', 'item', 'item', 'another_item']
我的列表实际上由多次出现的其他项目组成,所以我不能只找出哪个列表包含 'item' 出现次数最少的列表并迭代它,如果它包含更多出现 'another_item'。我还能尝试什么?
Counter from collections 能够处理多重集:
>>> from collections import Counter
>>> a = ['item', 'item', 'item', 'another_item']
>>> b = ['item', 'item', 'another_item']
# create counter objects for a and b
>>> ca = Counter(a)
>>> cb = Counter(b)
>>> intersection = ca & cb
>>> intersection
Counter({'item': 2, 'another_item': 1})
>>> list(intersection.elements())
['item', 'item', 'another_item']
您可以使用:
a = ['item','item','item', 'another_item']
b = ['item','item', 'another_item']
b, common = b[:], [ e for e in a if e in b and (b.pop(b.index(e)) or True)]
print(common) # ['item', 'item', 'another_item']
这有一个缺点,即需要创建其中一个列表的副本,因为列表理解将不得不删除迭代项。但是如果你切换 a 和 b 就可以了。
我有两个列表:
a = ['item.1','item.2','item.3', 'another_item']
b = ['item.4','item.5', 'another_item']
我将拆分元素以结束
a = ['item', 'item', 'item', 'another_item']
b = ['item', 'item', 'another_item']
我想找到实际的共享项目,最后得到
c = ['item','item', 'another_item']
但是set(a).intersection(b)
会return我['item', 'another_item']
和
c = [x for x in list1 if x in list2]
returns ['item', 'item', 'item', 'another_item']
我的列表实际上由多次出现的其他项目组成,所以我不能只找出哪个列表包含 'item' 出现次数最少的列表并迭代它,如果它包含更多出现 'another_item'。我还能尝试什么?
Counter from collections 能够处理多重集:
>>> from collections import Counter
>>> a = ['item', 'item', 'item', 'another_item']
>>> b = ['item', 'item', 'another_item']
# create counter objects for a and b
>>> ca = Counter(a)
>>> cb = Counter(b)
>>> intersection = ca & cb
>>> intersection
Counter({'item': 2, 'another_item': 1})
>>> list(intersection.elements())
['item', 'item', 'another_item']
您可以使用:
a = ['item','item','item', 'another_item']
b = ['item','item', 'another_item']
b, common = b[:], [ e for e in a if e in b and (b.pop(b.index(e)) or True)]
print(common) # ['item', 'item', 'another_item']
这有一个缺点,即需要创建其中一个列表的副本,因为列表理解将不得不删除迭代项。但是如果你切换 a 和 b 就可以了。