简体   繁体   English

使用相同的键合并元组

[英]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])]

and turn them into 并将它们变成

list_2 = [("AAA", [123, 456]), ("AAW", [147, 124])]

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: 最高效的方法是使用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])]

note that the converted data is probably better left as dictionary. 请注意,转换后的数据可能最好留作字典。 Converting to list again loses the "key" feature of the dictionary. 再次转换为列表会丢失字典的“关键”功能。

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. 另一方面,如果你想保留原始元组列表的“键”的顺序,除非你使用python 3.6 / 3.7,你必须创建一个包含原始“键”的列表(有序) ,unique),然后从字典重建列表。 Or use an OrderedDict but then you cannot use defaultdict (or use a recipe ) 或使用OrderedDict然后你不能使用defaultdict (或使用食谱

You can use a dict to keep track of the indices of each key to keep the time complexity O(n): 您可以使用dict来跟踪每个键的索引以保持时间复杂度O(n):

list_1 = [("AAA", [123]), ("AAA", [456]), ("AAW", [147]), ("AAW", [124])]
list_2 = []
i = {}
for k, s in list_1:
    if k not in i:
        list_2.append((k, s))
        i[k] = len(i)
    else:
        list_2[i[k]][1].extend(s)

list_2 would become: list_2将成为:

[('AAA', [123, 456]), ('AAW', [147, 124])]

You can create a dictionary and loop through the list. 您可以创建字典并循环遍历列表。 If the item present in dictionary append the value to already existing list else assign the value to key. 如果字典中的项目将值附加到现有列表,则将值分配给键。

dict_1 = {}
for item in list_1:
    if item[0] in dict_1:
        dict_1[item[0]].append(item[1][0])
    else:
        dict_1[item[0]] = item[1]
list_2 = list(dict_1.items())

Similarly to other answers, you can use a dictionary to associate each key with a list of values. 与其他答案类似,您可以使用字典将每个键与值列表相关联。 This is implemented in the function merge_by_keys in the code snippet below. 这是在下面的代码片段中的函数merge_by_keys中实现的。

import pprint

list_1 = [("AAA", [123]), ("AAA", [456]), ("AAW", [147]), ("AAW", [124])]

def merge_by_key(ts):

    d = {}
    for t in ts:
        key = t[0]
        values = t[1]
        if key not in d:
            d[key] = values[:]
        else:
            d[key].extend(values)

    return d.items()



result = merge_by_key(list_1)

pprint.pprint(result)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM