3 回答
TA贡献1794条经验 获得超7个赞
out = {}
for a, b, c in my_list:
out.setdefault(b, []).append((a, c))
out = [[k, [i for i, _ in v], [i for _, i in v]] for k, v in out.items()]
print(out)
印刷:
[['a', [0, 1, 5], ['0:00', '1:00', '5:00']],
['b', [2, 4, 8], ['2:00', '4:00', '8:00']],
['c', [3, 7], ['3:00', '7:00']],
['d', [6], ['6:00']],
['e', [9], ['9:00']]]
TA贡献1780条经验 获得超1个赞
另一种方法是使用itertools.groupby
import itertools
new_list = []
my_list = sorted(my_list, key=lambda row: row[1])
for name, groups in itertools.groupby(my_list, key=lambda row: row[1]):
groups = list(zip(*groups))
grouped_item = [name, groups[0], groups[2]]
new_list.append(grouped_item)
print(new_list)
[['a', (0, 1, 5), ('0:00', '1:00', '5:00')],
['b', (2, 4, 8), ('2:00', '4:00', '8:00')],
['c', (3, 7), ('3:00', '7:00')],
['d', (6,), ('6:00',)],
['e', (9,), ('9:00',)]]
TA贡献1836条经验 获得超5个赞
这是一种快速而肮脏的方法(与当前其他答案相同的效率,但更多的代码)
my_list = [[0, 'a', '0:00'],
[1, 'a', '1:00'],
[2, 'b', '2:00'],
[3, 'c', '3:00'],
[4, 'b', '4:00'],
[5, 'a', '5:00'],
[6, 'd', '6:00'],
[7, 'c', '7:00'],
[8, 'b', '8:00'],
[9, 'e', '9:00']]
tmp_dict = {}
for first, second, third in my_list:
if second not in tmp_dict:
tmp_dict[second] = [[],[]]
tmp_dict[second][0].append(first)
tmp_dict[second][1].append(third)
new_list = []
for key, val in tmp_dict.items():
new_list.append([key] + val)
print(new_list)
添加回答
举报