Python创建一个由唯一值组成的列表列表

时间:2018-05-16 21:46:34

标签: python list

在我的代码中,我有一个这样的列表:

l1 = [['var1', '2'], ['var1', '5'], ['var1', 'a'], ['var2', '90']]

我尝试生成一个从l1开始创建的代码:

[[['var1','2'],['var2','90']],[['var1','5'],['var2','90']],[['var1','a'], ['var2','90']]]

在实践中基于唯一值的三个不同列表,但我不知道如何执行此任务, 有没有特定的python函数来实现这个结果?

提前致谢

2 个答案:

答案 0 :(得分:2)

您可以在Python3中使用解压缩:

l1 = [['var1', '2'], ['var1', '5'], ['var1', 'a'], ['var2', '90']]
*l, _val = l1
l2 = [[i, _val] for i in l]

输出:

[[['var1', '2'], ['var2', '90']], [['var1', '5'], ['var2', '90']], [['var1', 'a'], ['var2', '90']]]

答案 1 :(得分:2)

看起来你需要首先对你的第一个元素进行分组

from itertools import groupby, product
from operator import itemgetter

grps = [list(grp) for _, grp in groupby(l1, key=itemgetter(0))]
# itemgetter(0) is the default, but this is somewhat more explicit.

然后在这些群组上使用itertools.product

result = product(*grps)

这会给你:

>>> l1 = [['var1', '2'], ['var1', '5'], ['var1', 'a'], ['var2', '90']]
result = [(['var1', '2'], ['var2', '90']), (['var1', '5'], ['var2', '90']), (['var1', 'a'], ['var2', '90'])]
>>> l2 = [['var1', '7'], ['var2', '2'], ['var2', '5']]
result = [(['var1', '7'], ['var2', '2']), (['var1', '7'], ['var2', '5'])]

您的最终功能将变为:

from itertools import groupby, product
from operator import itemgetter

def product_by_grouping(lst):
    grps = [list(grp) for _, grp in groupby(lst, key=itemgetter(0))]
    return product(*grps)