首页 > 解决方案 > 将列表组合到列表列表中,其中匹配项位于列表内的同一列表中

问题描述

我有两个列表,我想将它们组合成一个列表,其中列表中的对象是两个列表之间的匹配列表,但也包括不匹配的对象。

由于我是 python 新手,我什至不知道从哪里开始得到这个结果。

两个列表:

husband = ['cat','dog','bunny']
wife = ['dog','bunny','horse']

我想要的结果:

farm = [['cat'],['dog','dog'],['bunny','bunny'],['horse']]

标签: pythonlistobject

解决方案


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]

推荐阅读