python - 将列表组合到列表列表中,其中匹配项位于列表内的同一列表中
问题描述
我有两个列表,我想将它们组合成一个列表,其中列表中的对象是两个列表之间的匹配列表,但也包括不匹配的对象。
由于我是 python 新手,我什至不知道从哪里开始得到这个结果。
两个列表:
husband = ['cat','dog','bunny']
wife = ['dog','bunny','horse']
我想要的结果:
farm = [['cat'],['dog','dog'],['bunny','bunny'],['horse']]
解决方案
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]
推荐阅读
- tizen-wearable-sdk - Tizen 修改标签文本
- python - 未找到“fobi.dashboard”的反向。“fobi.dashboard”不是有效的视图函数或模式名称
- wordpress - 如何循环浏览 wordpress 帖子并在最后一页上使用没有重复的 posts_per_page?
- java - 无法使用自定义视图在画布上绘图
- dask - 使用 Dask 读取块结构的 ASCII 文件
- sql - 使用合并到多行
- html - 在不同的 div 中对齐元素
- powershell - 试图通过 NAME 和 CPU 时间杀死一个进程
- php - 'simplexml' php 到 mysql 数据库循环仅返回第一个元素
- java - 按特定类型的 HTML 标记拆分字符串