Adding elements based on the repeated elements in list of lists in Python

时间:2018-04-18 17:55:15

标签: python list elements

sorted_lst = [
['04-0200', 'str1', '1', 'n1'],
['04-0200', 'str2', '6', 'n1,n2,n3,n4,n5,n6'],
['11-0200', 'str3', '1', 'u1'],
['19-0000', '', '2', ''], 
['19-0201', 'str4', '2', ''],
['19-0201', 'str10', '3', 'p1,p2,p3'], 
['22-0001', 'str5', '5', 'a1,a2,a3,a4'],
['22-0001', 'str6', '184', 'b1,b2,b3,b4,b5'], 
['22-0001', 'str7', '2', 'c1,c2'], 
['9-02011', 'str8', '3', '', 'x,y,z']
]

I have a sorted list that will have a list of lists with repeated index0. Based on the index0 from each list, i will have to add the index3 and then join the strings in index4. Index#3 will be always numbers - this should be added if there is any repeated index#0 Index#4 could be anything - this should be merged and there shouldn't be any repeated strings/numbers after merge.

As an example, the result of the above list should be something like:

final_lst = [
['04-0200', 'str1', '7', 'n1,n2,n3,n4,n5,n6'],
['11-0200', 'str3', '1', 'u1'],
['19-0000', '', '2', ''], 
['19-0201', 'str4', '5', 'p1,p2,p3'],
['22-0001', 'str5', '191', 'a1,a2,a3,a4,b1,b2,b3,b4,b5,c1,c2'],
['9-02011', 'str8', '3', '', 'x,y,z']
]

====================================================================== Edited: Sorry, new to the community; adding more details. Please close the thread; was able to merge them.

1 个答案:

答案 0 :(得分:0)

我能够实现我想要的...... 帖子可以关闭。

合并项目:

[('04-0200', 'str1', 7, 'n1,n2,n3,n4,n5,n6'), 
('11-0200', 'str3', '1', 'u1'),
('19-0000', '', '2', ''),
('19-0201', 'str4', 5, 'p1,p2,p3'), 
('22-0001', 'str5', 191, 'a1,a2,a3,a4b1,b2,b3,b4,b5c1,c2'), 
('9-02011', 'str8', '3', '')]
相关问题