Pergunta

I am looking for a way to do this in Python without much boiler plate code.

Assume I have a list:

[(a,4),(b,4),(a,5),(b,3)]

I am trying to find a function that will allow me to sort by the first tuple value, and merge the list values together like so:

[(a,[4,3]),(b,[4,5])]

I know I can do this the naive way but I was wondering if there was a better way.

Foi útil?

Solução

Use collections.defaultdict(list):

from collections import defaultdict

lst = [("a",4), ("b",4), ("a",5), ("b",3)]

result = defaultdict(list)
for a, b in lst:
    result[a].append(b)

print sorted(result.items())

# prints: [('a', [4, 5]), ('b', [4, 3])]

Before the sort the algorithm has O(n) complexity; the group by algorithm has O(n * log(n)) and the set/list/dict comprehension has something greater than O(n^2)

Outras dicas

Assuming that 'a' is your initial list an 'b' is the expected result, the following code will work:

d = {}
for k, v in a:
    if k in d:
        d[k].append(v)
    else:
        d[k] = [v] 
b = d.items()

Not so efficient, but enough (with set + list + dict comprehension):

>>> data = [("a",4), ("b",4), ("a",5), ("b",3)]
>>> {key: [v for k, v in data if k == key]
...  for key in {k for k, v in data}
... }.items()
[('a', [4, 5]), ('b', [4, 3])]

Another option (again assuming 'a' is the initial list)

[(key,[v2 for k2, v2 in a if k2 == key ]) for key in list(set(map(lambda x: x[0], a)))]
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top