Home > other >  Two dimensional list in python having similar values and merging them
Two dimensional list in python having similar values and merging them

Time:09-28

I have a list.

shopping_record_list = [
                        [2,  'TeaSet', 39.95, 5],
                        [2,  'TeaSet', 39.95, 6],
                        [34, 'CitrusCather', 19.95, 5],
                        [4,  'KnifeBlockSet', 99.95, 1],
                        [4,  'KnifeBlockSet', 99.95, 1]
                       ]

I need this list as

shopping_record_list = [
                        [2,  'TeaSet', 39.95, 11],
                        [34, 'CitrusCather', 19.95, 5],
                        [4,  'KnifeBlockSet', 99.95, 2]
                       ]

How can I do this?

CodePudding user response:

shopping_record_list = [
  [2,  'TeaSet', 39.95, 5],
  [2,  'TeaSet', 39.95, 6],
  [34, 'CitrusCather', 19.95, 5],
  [4,  'KnifeBlockSet', 99.95, 1],
  [4,  'KnifeBlockSet', 99.95, 1]
 ]

def aggregate(list_):
  results={}
  for i in list_:
    if i[0] in results:
      results[i[0]][3]  = i[3]
    else:
      results[i[0]] = i
  return results

print(aggregate(shopping_record_list))

Result:

{
  2: [2, 'TeaSet', 39.95, 11],
  34: [34, 'CitrusCather', 19.95, 5],
  4: [4, 'KnifeBlockSet', 99.95, 2]
}

And for the aggregated values only:

...

print(aggregate(shopping_record_list).values())

Result:

[
  [2, 'TeaSet', 39.95, 11],
  [34, 'CitrusCather', 19.95, 5],
  [4, 'KnifeBlockSet', 99.95, 2]
]

CodePudding user response:

With itertools.groupby you can do:

[
    [*k, sum([e[-1] for e in g])]
    for k, g in itertools.groupby(shopping_record_list, lambda x: x[:-1])
]

output:

[[2, 'TeaSet', 39.95, 11],
 [34, 'CitrusCather', 19.95, 5],
 [4, 'KnifeBlockSet', 99.95, 2]]
  • Related