full_l = husband + wife
unique_l = list(dict.fromkeys(full_l))
# unique list with order preserved, if you dont want to preserve order, you can just use set(full_l)
output = [[animal] * full_l.count(animal) for animal in unique_l]
In [25]: husband = ["cat","dog","bunny"]
...: wife = ["dog","bunny","horse"]
In [26]: husband_set = set(husband)
In [27]: wife_set = set(wife)
In [28]: data = []
In [29]: data.extend([[i] * 2 for i in wife_set.intersection(husband_set)])
In [30]: data.append([i for i in husband_set.difference(wife_set)])
In [31]: data.append([i for i in wife_set.difference(husband_set)])
In [32]: data
Out[32]: [['dog', 'dog'], ['bunny', 'bunny'], ['cat'], ['horse']]
from collections import Counter,defaultdict
husband = ['cat','dog','bunny']
wife = ['dog','bunny','horse']
print([[k] * v for k , v in Counter(husband + wife).items()])
#or
farm = defaultdict(list)
for v in husband + wife:
farm[v].append(v)
print(farm.values())
使用集合
下面是使用
collections
模块的两种方法相关问题 更多 >
编程相关推荐