0

If I have two separated lists:

list1 = [['2021-05-24', '31220'],....., ['2021-05-24', '6640'],['2021-05-10', '8830'].....]

list2 = [['2021-05-24', '77860'],.....,['2021-05-24', '438000'],['2021-05-10', '9990'].....]

How could I combine them to [['2021-05-24', 'add all numbers in '2021-05-24' together'],['2021-05-10', 'add all numbers in '2021-05-10' together']] , '.....' means there are many list-tuples

I am considering delete the duplicated date in each list and then add two lists up:

import networkx as nx
G = nx.Graph()
G.add_nodes_from(sum(list2, []))
q = [[(s[i],s[i+1]) for i in range(len(s)-1)] for s in list2]
for i in q:
    G.add_edges_from(i)
print([list(i) for i in nx.connected_components(G)])

but my code not only deleted the same dates but also deleted the same numbers. Thanks in advance.

  • 2
    I think you provided the wrong code snippet... I am failing to see how it even tries to do what you describe. Anyway, see [this](https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-a-list-of-lists) on flattening lists, and [this](https://www.geeksforgeeks.org/python-ways-to-remove-duplicates-from-list/) to remove duplicates, although there may be more optimized ways to do that together. – Sean AH Jul 15 '21 at 17:15
  • 1
    Can you please edit your question and put there example output? – Andrej Kesely Jul 15 '21 at 17:16

2 Answers2

1

I'd recommend using a defaultdict:

from collections import defaultdict
result = defaultdict(int)
for k,v in (list1 + list2):
    result[k] += v

Then you can convert the dict back to a list. Of course if you have several lists you may want to use itertools.chain instead of list1 + list2

gimix
  • 3,431
  • 2
  • 5
  • 21
0

You can go with creating new dictionary and do calculation and then create list out of it. Here is the code for that

result={}
for i in list1+list2: #creating dict and doing calculation
    if i[0] in result.keys():
        result[i[0]] += int(i[1])
    else:
        result[i[0]] = int(i[1])

result_list = [[key, result[key]] for key in result] #converting dict to expected list
print(result_list)