htetmyet htetmyet -4 years ago 95
Python Question

Sum up member elements' values in a list matching the word from a tuple in Python 2.7

I would like to sum up each element in a list which values can be achieved by matching the words from a list. A tuple containing values of each word and a list have phrases are as below:

val_tuple = [('and',3),('cat',2),('dog',3),('only',5),('horse',3),('car',3),...]

word_list = ['cat and dog',
'only horse',
'dog and horse',
'only dog',...]

The output should be like this:

result = [('cat and dog', 8),
('only horse', 8),
('dog and horse', 9),
('only dog', 8),...]

I couldn't figure out a way and stuck with several attempts just to sum up the values in list:

for w in word_list:
for val in val_tuple:
if val[0] in w:
sum = val[0]
sum += sum

Answer Source

First of all you better construct a dictionary for your word values:

word_values = dict(val_tuple)

You can simply use list comprehension:

result = [(sentence,sum(word_values.get(word,0) for word in sentence.split()))
              for sentence in word_list]

The boldface part sums the scores up. So what we do for every sentence is that we use .split() to obtain the words. Now for each of these words we obtain the word_values.get(word,0): this means we perform a lookup and if the element is not found, we assume word value 0. We sum(..) over all these values and return a tuple (sentence,sum(..)) for each of these sentences.

Based on the provided sample data, I obtain:

>>> result
[('cat and dog', 8), ('only horse', 8), ('dog and horse', 9), ('only dog', 8)]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download