最有效的方法是使用collections.defaultdict https://docs.python.org/3/library/collections.html#collections.defaultdict字典将数据存储为扩展列表,然后根据需要转换回元组/列表:
import collections
list_1 = [("AAA", [123]), ("AAA", [456]), ("AAW", [147]), ("AAW", [124])]
c = collections.defaultdict(list)
for a,b in list_1:
c[a].extend(b) # add to existing list or create a new one
list_2 = list(c.items())
result:
[('AAW', [147, 124]), ('AAA', [123, 456])]
请注意,转换后的数据最好保留为字典。再次转换为列表就失去了字典的“关键”功能。
另一方面,如果您想保留原始元组列表中“键”的顺序,除非您使用的是 python 3.6/3.7,否则您必须使用原始“键”创建一个列表(按顺序排列) ,唯一),然后从字典中重建列表。或者使用OrderedDict
但你不能使用defaultdict
(或使用recipe https://stackoverflow.com/questions/6190331/can-i-do-an-ordered-default-dict-in-python)