Home > Net >  How to append nested lists with same string together?
How to append nested lists with same string together?

Time:04-06

I have a nested list that looks like the following:

list = [['bob', '12'], ['jim', '14'], ['bob', '13']]

I am trying to get the following output:

list = [['bob', '12', '13'], ['jim', '14']]

Is there any way this can be achieved. I can only truncate the nested lit to remove the values, but not add them into another list. Any help would be appreciated. Thanks. I have tried the following:

i = 0
while i < len(list):
  find = list[i][0]
  for a, b in list:
    if find == a:
      list[i]].append(b)
i  = 1

CodePudding user response:

One option is to use a temporary dictionary as you combine lists:

tmp = {}
for name, num in lst:
    if name in tmp:
        tmp[name].append(num)
    else:
        tmp[name] = [name, num]
out = list(tmp.values())

Output:

[['bob', '12', '13'], ['jim', '14']]

As a side note, when you use list as a variable name, you can’t use list() constructor afterwards as the variable name shadows it. So it’s better to name your variable something else. I named it lst here.

CodePudding user response:

A dirty one liner :-D

[[k,*v] for k,v in {_ld:[_l[1] for _l in l if _l[0]==_ld] for _ld in {_l[0] for _l in l }}.items()]
  • Related