元组列表到列表列表中,并具有元素分组

时间:2018-10-16 10:48:16

标签: python python-3.x list dictionary nested

我有一个元组列表:

start_list = [(A99, 2, 3 B1), (A21, 3, 4, B1), (A123, 4, 5, B2), (A22, 3 6, B2), (A12, 4, 6, B1)]

并且我想将具有相同最后一个元素的所有元组分组为以下形式的列表:

result = [[B1, [A99, A21, A12]],[B2, [A123, A22]]]

我的尝试

for idx in range(len(start_list)):
        concat_list += [start_list[idx][0]]
        for idx2 in range(idx+1, len(start_list)):
            if start_list[idx][-1] == start_list[idx2][-1]:
                concat_list += [start_list[idx2][0]]

        grouped_list.append([start_list[idx][-1], concat_list])
        concat_list = []

    grouped_list = dict(((x[0]), x) for x in grouped_list).values()

它没有考虑所有元组,也没有将所有初始元素(A99,A123 ...)包括在相应的元组中。

2 个答案:

答案 0 :(得分:2)

您可以将collections.defaultdict用于O( n )解决方案:

from collections import defaultdict

start_list = [('A99', 2, 3, 'B1'), ('A21', 3, 4, 'B1'), ('A123', 4, 5, 'B2'),
              ('A22', 3, 6, 'B2'), ('A12', 4, 6, 'B1')]

res = defaultdict(list)

for value, _, _, key in start_list:
    res[key].append(value)

结果:

defaultdict(list, {'B1': ['A99', 'A21', 'A12'],
                   'B2': ['A123', 'A22']})

如果您不介意tuple元素,则可以使用嵌套结构:

res_lst = list(res.items())

[('B1', ['A99', 'A21', 'A12']), ('B2', ['A123', 'A22'])]

或者为获得精确的所需输出,请使用列表理解:

res_lst = [[k, v] for k, v in res.items()]

[['B1', ['A99', 'A21', 'A12']], ['B2', ['A123', 'A22']]]

答案 1 :(得分:0)

您可以尝试类似的方法:

function dxdt = lv(t,x,p)

dxdt = 25.7+x*(0.00038*x-0.00000014*x^2)-x*(0.162+0.00000006*x^2)-p*x;
end
相关问题