Question

I have put together a list called word_list:

print(word_list)

['deal', 5, 'price', 4, 'deal', 6, 'deal', '4', 'huge', '2', '$', '2', 'won', '3']

My goal with this list is to somehow combine the word with the value that follows it and when the work is done the list should look something like this:

print(worked_word_list)

['deal', 15, 'price', 4, 'huge', '2', '$', '2', 'won', '3']

I was thinking about first making it a dictionary, but I could really use some guidance on how to proceed from here.

Was it helpful?

Solution

You can do it as follows:

from collections import defaultdict
from itertools import chain

a = ['deal', 5, 'price', 4, 'deal', 6, 'deal', '4', 'huge', '2', '$', '2', 'won', '3']

d = defaultdict(int)
for x,y in zip(a[::2],a[1::2]):
    d[x] += int(y)

print list(chain.from_iterable((i,j) for i,j in d.items()))

[OUTPUT]
['huge', 2, 'price', 4, 'won', 3, '$', 2, 'deal', 15]

Hope that helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top