python - 合并两个长度不等的元组列表
问题描述
如何合并两个不相等的元组列表:
x = [('Animal', 1), ('Bird', 2)]
y = [('Animal', 'Dog'), ('Animal', 'Cat'), ('Bird', 'Parrot')]
..要得到..
[('Animal', 1, 'Dog'), ('Animal', 1, 'Cat'), ('Bird', 2, 'Parrot')]
..使用列表理解?
解决方案
变成x
字典方便查找,然后...
xx = dict(x)
[(k, xx[k], a) for k, a in y]
# => [('Animal', 1, 'Dog'), ('Animal', 1, 'Cat'), ('Bird', 2, 'Parrot')]
编辑:现在这是一个完全不同的问题。
[(k, n, a) for k, a in y for kk, n in x if kk == k]
# => [('Animal', 1, 'Dog'), ('Animal', 2, 'Dog'), ('Animal', 1, 'Cat'),
# ('Animal', 2, 'Cat'), ('Bird', 2, 'Parrot')]
x
您可以通过将动物字典转换为数字列表来再次加快速度。
推荐阅读
- flutter - 您好,我想知道如何在颤振中同时使用 java + kotlin 实际上我想使用这两种语言在颤振中创建自己的应用程序
- java - 调试多线程 Java 应用程序
- debugging - 更新 liquibase 到 3.8.9 调试日志默认开始出现
- flutter - 如何编辑 CupertinoSegmentedControl?
- python - 使用 PyCharm 从 root 中名为“test”的目录运行 unittest 不起作用
- mysql - SQL查询更多时间执行并最终出错
- angular - 是否可以在旧计算机上构建 Angular 代码
- docker - 将 jmeter.log 也发送到控制台标准输出
- node.js - 如何通过 https 在生产环境中部署 React 应用程序?
- python-3.x - 安装pandas-profiling后尝试导入,遇到问题