Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Clumping' a list in python

Tags:

python

I've been trying to 'clump' a list

I mean putting items together depending on the item inbetween, so ['d','-','g','p','q','-','a','v','i'] becomes ['d-g','p','q-a','v','i'] when 'clumped' around any '-'

Here's my attempt:

def clump(List):
    box = []
    for item in List:
        try:
            if List[List.index(item) + 1] == "-":
                box.append("".join(List[List.index(item):List.index(item)+3]))
            else:
                box.append(item)

        except:
            pass

    return box

However, it outputs (for the example above)

['d-g', '-', 'g', 'p', 'q-a', '-', 'a', 'v']

As I have no idea how to skip the next two items

Also, the code is a complete mess, mainly due to the try and except statement (I use it, otherwise I get an IndexError, when it reaches the last item)

How can it be fixed (or completely rewritten)?

Thanks

like image 529
Oliver.G Avatar asked May 29 '26 05:05

Oliver.G


1 Answers

Here's an O(n) solution that maintains a flag determining whether or not you are currently clumping. It then manipulates the last item in the list based on this condition:

def clump(arr):
     started = False
     out = []
     for item in arr:
         if item == '-':
             started = True
             out[-1] += item
         elif started:
             out[-1] += item
             started = False
         else:
              out.append(item)
     return out

In action:

In [53]: clump(x)
Out[53]: ['d-g', 'p', 'q-a', 'v', 'i']

This solution will fail if the first item in the list is a dash, but that seems like it should be an invalid input.

like image 69
user3483203 Avatar answered May 31 '26 17:05

user3483203



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!