首页 > 解决方案 > 创建不同列表的元组列表

问题描述

假设我有以下三个列表(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'), ...]

`

标签: pythonzip

解决方案


正如其他人已经说过的,使用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')]

推荐阅读