合并具有相同键的元组 [英] Merge tuples with the same key
问题描述
如何合并具有相同键的元组
How to merge a tuple with the same key
list_1 = [("AAA", [123]), ("AAA", [456]), ("AAW", [147]), ("AAW", [124])]
然后把它们变成
list_2 = [("AAA", [123, 456]), ("AAW", [147, 124])]
推荐答案
最高效的方法是使用 collections.defaultdict
字典将数据存储为扩展列表,然后在需要时转换回元组/列表:
The most performant approach is to use a collections.defaultdict
dictionary to store data as an expanding list, then convert back to tuple/list if needed:
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())
结果:
[('AAW', [147, 124]), ('AAA', [123, 456])]
请注意,转换后的数据最好保留为字典.再次转换为list,失去了字典的key"特性.
note that the converted data is probably better left as dictionary. Converting to list again loses the "key" feature of the dictionary.
另一方面,如果您想保留原始元组列表的键"的顺序,除非您使用的是python 3.6/3.7,否则您必须使用原始键"创建一个列表"(有序,唯一),然后从字典中重建列表.或者使用 OrderedDict
但你不能使用 defaultdict
(或使用 食谱)
On the other hand, if you want to retain the order of the "keys" of the original list of tuples, unless you're using python 3.6/3.7, you'd have to create a list with the original "keys" (ordered, unique), then rebuild the list from the dictionary. Or use an OrderedDict
but then you cannot use defaultdict
(or use a recipe)
这篇关于合并具有相同键的元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!