Home > Mobile >  Merge two list of lists according to first element in python
Merge two list of lists according to first element in python

Time:10-11

I have list of lists in python, each one have item represented as string

I tried to do something like :

return [a   [b[1]] for (a, b) in zip(buffer[0], buffer[1])]

where buffer is the name of list of lists, but at first it's static, but in this case only i have two list, but also I can have more than two lists in side the buffer so I need it more dynamic , and also this code is not working.

TypeError: can only concatenate str (not "list") to str

can Anyone help please ?

CodePudding user response:

One way would be to build an intermediate dictionary keyed on the first token of each sub-list - i.e., Term1, Term2 etc

Once you have that you can build a new list from the dictionary content.

Something like this:

list_of_lists = [
    ['Term1,3,d3,d5,d43 ', 'Term2,3,d1,d15,d46 ', 'Term3,3,d3,d5,d43'],
    ['Term1,3,d4,d6,d7', 'Term2,3,d2,d3,d4', 'Term3,3,d5,d6,d77']
]

td = {}

for e in list_of_lists:
    for s in e:
        t = s.strip().split(',')
        td.setdefault(t[0], []).extend(t[2:])

nl = []

for k, v in td.items():
    v = set(v)
    sd = ','.join(sorted(v, key=lambda x: int(x[1:])))
    nl.append(f'{k},{len(v)},{sd}')

print(nl)

Output:

['Term1,6,d3,d4,d5,d6,d7,d43', 'Term2,6,d1,d2,d3,d4,d15,d46', 'Term3,5,d3,d5,d6,d43,d77']

Note:

The sort key only works for data where there is exactly 1 letter preceding the digits - e.g., d43. If these values were something like dd43, you'd need to do some extra work

  • Related