在2D python列表中附加值

时间:2019-05-22 08:59:28

标签: python

我在python中有一个列表

issuelist=[["k1","v1"],["k2","v2"],["k3","v1"],["k4","v2"],["k5","v2"],["k6","v3"],["k7","v1"]]

我想将此列表的值附加到另一个列表中,使得如果issuelist[x][1]==issuelist[y][1]的值可以得到类似的内容

Buildlist=[["k1","k3","k7"],["k2","k4","k5"],["k6"]]

issuelist=[["k1","v1"],["k2","v2"],["k3","v1"],["k4","v2"],["k5","v2"],["k6","v3"],["k7","v1"]]
count=len(issuelist)
buildlist = [[]]* count
for i in range(len(issuelist)):
    for j in range(len(issuelist)):
        if issuelist[i][1]==issuelist[j][1]:
            buildlist[i].append(issuelist[j][0])

这是我现在尝试过的,但无法获得期望的结果。任何帮助将不胜感激

2 个答案:

答案 0 :(得分:4)

使用itertools.groupby

例如:

from itertools import groupby

issuelist = [["k1","v1"],["k2","v2"],["k3","v1"],["k4","v2"],["k5","v2"],["k6","v3"],["k7","v1"]]
result = {k: [i[0] for i in v ]for k, v in groupby(sorted(issuelist, key=lambda x: x[1]), lambda x: x[1])}
print(result)
print(list(result.values()))

输出:

{'v1': ['k1', 'k3', 'k7'], 'v2': ['k2', 'k4', 'k5'], 'v3': ['k6']}
[['k1', 'k3', 'k7'], ['k2', 'k4', 'k5'], ['k6']]

答案 1 :(得分:0)

尝试一下:

from collections import defaultdict
issuelist = [["k1","v1"],["k2","v2"],["k3","v1"],["k4","v2"],["k5","v2"],["k6","v3"],["k7","v1"]]
result = defaultdict(list)
for inner_list in issuelist:
    result[inner_list[1]].append(inner_list[0])

result_array = list(result.values())
rint(presult_array)