Join repeated items in a list

2

I try to get that from the result of a function that is returning me lists of words like the following:

[('algo', 1), ('de', 1), ('una', 1), ('de', 1), ('una', 1), ('y', 1), ('otra', 1), ('cabeza', 1), ('', 1)]

that another function I go picking up these lists and I create lists with which they are equal, that is to say that I result of something like this:

[('una', 1), ('una', 1)]
[('de', 1), ('de', 1)]
[('algo', 1)]
[('y', 1)]
...
    
asked by Radega 29.03.2018 в 11:31
source

1 answer

2

In the collections module (python standard) you have the Counter() class that makes you a good part of the "dirty work".

That class you spend an iterable (in this case your list) and goes looking for repeated elements. It returns a dictionary whose keys are the elements of the list, and whose values are the number of repetitions of each.

For example:

>>> import collections
>>> l = [('algo', 1), ('de', 1), ('una', 1), ('de', 1), ('una', 1), ('y', 1), ('otra', 1), ('cabeza', 1), ('', 1)]
>>> collections.Counter(l)
Counter({('', 1): 1,
         ('algo', 1): 1,
         ('cabeza', 1): 1,
         ('de', 1): 2,
         ('otra', 1): 1,
         ('una', 1): 2,
         ('y', 1): 1})

To obtain the list that you ask in the question, it is enough to use this result provided by Counter to create it. Just repeat each element indicated in the key the number of times indicated in the value:

>>> [[k]*v for k, v in collections.Counter(l).items()]
[[('algo', 1)],
 [('de', 1), ('de', 1)],
 [('una', 1), ('una', 1)],
 [('y', 1)],
 [('otra', 1)],
 [('cabeza', 1)],
 [('', 1)]]
    
answered by 29.03.2018 / 12:16
source