列表合并问题:在一定条件下合并二维数组
Merge of list problem: merging two-dimensional array under certain conditions
如果前两个 index('2021-03-18'
, 'Night'
) 相同,我想合并 test_list
中的第三个索引(数字列表)。
例如:
test_list
:
[['2021-03-18', 'Night', [9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, 22, 23, 24, 25, 26, 27]],\
['2021-03-18', 'Night',[46, 47, 48, 49, 50, 51, 53, 54, 55, 56, 57, 58, 59]],
['2021-03-19','Other', [33, 34, 35, 36, 37, 38, 57,58,59]]]
如何将其合并到这样的列表中?
期望的结果:
['2021-03-18', 'Night', [9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, 22, 23, 24, 25, 26, 27, 46, 47, 48, 49, 50, 51, 53, 54, 55, 56, 57, 58, 59]],
['2021-03-19', 'Other', [33, 34, 35, 36, 37, 38, 57,58,59]]
]
test_list = [['2021-03-18', 'Night', [9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, 22, 23, 24, 25, 26, 27]], \
['2021-03-18', 'Night', [46, 47, 48, 49, 50, 51, 53, 54, 55, 56, 57, 58, 59]], \
['2021-03-19','Other', [33, 34, 35, 36, 37, 38, 57,58,59]]]
d = {}
for date, key, lst in test_list:
if (date, key) in d:
d[(date, key)] += lst
else:
d[(date, key)] = lst
result = [list(key) + item for key, item in d.items()]
如果前两个 index('2021-03-18'
, 'Night'
) 相同,我想合并 test_list
中的第三个索引(数字列表)。
例如:
test_list
:
[['2021-03-18', 'Night', [9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, 22, 23, 24, 25, 26, 27]],\
['2021-03-18', 'Night',[46, 47, 48, 49, 50, 51, 53, 54, 55, 56, 57, 58, 59]],
['2021-03-19','Other', [33, 34, 35, 36, 37, 38, 57,58,59]]]
如何将其合并到这样的列表中?
期望的结果:
['2021-03-18', 'Night', [9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, 22, 23, 24, 25, 26, 27, 46, 47, 48, 49, 50, 51, 53, 54, 55, 56, 57, 58, 59]],
['2021-03-19', 'Other', [33, 34, 35, 36, 37, 38, 57,58,59]]
]
test_list = [['2021-03-18', 'Night', [9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, 22, 23, 24, 25, 26, 27]], \
['2021-03-18', 'Night', [46, 47, 48, 49, 50, 51, 53, 54, 55, 56, 57, 58, 59]], \
['2021-03-19','Other', [33, 34, 35, 36, 37, 38, 57,58,59]]]
d = {}
for date, key, lst in test_list:
if (date, key) in d:
d[(date, key)] += lst
else:
d[(date, key)] = lst
result = [list(key) + item for key, item in d.items()]