python - 创建不同列表的元组列表
问题描述
假设我有以下三个列表(l1、l2、l3)。如何创建一个新列表,其中每个元素都是列表元素的元组(l_desired)?它实际上是 python 中 zip 方法的扩展版本。
简而言之,给定l1, l2, l3
,我该如何创建l_desired
?
l1 = [1,2,3]
l2 = ['a', 'b', 'c']
l3 = ['Jess', 'Muss']
l_desiered = [(1, 'a', 'Jess'), (1, 'b', 'Jess'), (1, 'c', 'Jess'),
(1, 'a', 'Muss'), (1, 'b', 'Muss'), (1, 'c', 'Muss'),
(2, 'a', 'Jess'), (2, 'b', 'Jess'), (2, 'c', 'Jess'), ...]
`
解决方案
正如其他人已经说过的,使用itertools.product()
:
>>> l1 = [1,2,3]
>>> l2 = ['a', 'b', 'c']
>>> l3 = ['Jess', 'Muss']
>>> list(itertools.product(l1, l2, l3))
[(1, 'a', 'Jess'), (1, 'a', 'Muss'), (1, 'b', 'Jess'), (1, 'b', 'Muss'), (1, 'c', 'Jess'), (1, 'c', 'Muss'), (2, 'a', 'Jess'), (2, 'a', 'Muss'), (2, 'b', 'Jess'), (2, 'b', 'Muss'), (2, 'c', 'Jess'), (2, 'c', 'Muss'), (3, 'a', 'Jess'), (3, 'a', 'Muss'), (3, 'b', 'Jess'), (3, 'b', 'Muss'), (3, 'c', 'Jess'), (3, 'c', 'Muss')]
要实现问题中指定的排序顺序,您可以对结果进行如下排序:
>>> from operator import itemgetter
>>> sorted(itertools.product(l1, l2, l3), key=itemgetter(0,2,1))
[(1, 'a', 'Jess'), (1, 'b', 'Jess'), (1, 'c', 'Jess'), (1, 'a', 'Muss'), (1, 'b', 'Muss'), (1, 'c', 'Muss'), (2, 'a', 'Jess'), (2, 'b', 'Jess'), (2, 'c', 'Jess'), (2, 'a', 'Muss'), (2, 'b', 'Muss'), (2, 'c', 'Muss'), (3, 'a', 'Jess'), (3, 'b', 'Jess'), (3, 'c', 'Jess'), (3, 'a', 'Muss'), (3, 'b', 'Muss'), (3, 'c', 'Muss')]
推荐阅读
- sql - 可选择运行派生表。使用“where 子句”或“连接条件”更快地排除数据
- python - Kivy,鼠标周围不透明,显示图片
- python - Microsoft-Graph:无法从 python 代码获取令牌:错误 SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED]
- python - 根据特定列的相等文本加入数据库
- django - 我想在 django rest 框架上设置一个 API,就像它一样 https://docs.microsoft.com/en-us/rest/api/power-bi/reports/get-reports-in-group#code-try-0
- javascript - 如何通过dataTable中的复选框或单选按钮选择记录
- c# - 为什么 Content-Disposition UTF8 格式在一种情况下有效但在另一种情况下失败
- html - 格式化标题仍显示原始默认标题
- typescript - 打字稿类型“T”不能分配给类型“数字”
- http - 通过 HTTP 客户端记录所有 HTTP 请求和响应