Home > database >  Separate same values in list of list - Python
Separate same values in list of list - Python

Time:08-19

I have a list

l=[('a', 120), ('b', 2039), ('b', 0), ('c', 98), ('a', 34), ('a', 0), ('h', 46), ('c', 78)]

I want to convert this list like this -

l=[
       [('a', 120), ('a', 34), ('a', 0)], 
       [('b', 2039), ('b', 0)],
       [('c', 98), ('c', 78)], 
       [('h', 46)],
   ]

How to achieve this conversion in python list in less time, thanks

CodePudding user response:

Not sure if this does it in "less time" because there are no comparative timing data. Here are two versions. One that uses defaultdict from the collections module and one that utilises a dictionary's built-in functionality.

In case you're tempted to use defaultdict, note that it's marginally slower than the alternative.

from collections import defaultdict
from timeit import timeit

l = [('a', 120), ('b', 2039), ('b', 0), ('c', 98),
     ('a', 34), ('a', 0), ('h', 46), ('c', 78)]

def func_1(l):
    d = {}
    for k, v in l:
        d.setdefault(k, []).append((k, v))
    return list(d.values())

def func_2(l):
    d = defaultdict(list)
    for k, v in l:
        d[k].append((k, v))
    return list(d.values())

for func in func_1, func_2:
    print(func.__name__, timeit(lambda: func(l)))

Output:

func_1 1.1978088119999484
func_2 1.3840169149998474

CodePudding user response:

There are probably better ways but this is what I came up with is vanilla.

l=[('a', 120), ('b', 2039), ('b', 0), ('c', 98), ('a', 34), ('a', 0), ('h', 46), ('c', 78)]

tmp_l = {}
for key,value in l:
  if tmp_l.get(key) is not None:
    tmp_l[key].append(value)
    continue

  tmp_l[key]=[value]

result = []
for key, value in tmp_l.items():
  result.append([(key, item) for item in value])

print(result)

CodePudding user response:

You could do it thusly if you are simply looking to nest comprehensions:

data = [('a', 120), ('b', 2039), ('b', 0), ('c', 98), ('a', 34), ('a', 0), ('h', 46), ('c', 78)]

print( sorted( [entry for entry in data if entry[0] == label] for label in set([label for (label, _) in data]) ) )

Be aware that if this is just a homework assignment, you are only hurting yourself by failing both to explore the language and to practice your skills in problem solving.

  • Related