This code works but I was wondering if there is a more pythonic way for writing it.
word_frequency
is a dictionary of lists, e.g.:
word_frequency = {'dogs': [1234, 4321], 'are': [9999, 0000], 'fun': [4389, 3234]}
vocab_frequency = [0, 0] # stores the total times all the words used in each class
for word in word_frequency: # that is not the most elegant solution, but it works!
vocab_frequency[0] += word_frequency[word][0] #negative class
vocab_frequency[1] += word_frequency[word][1] #positive class
Is there a more elegant way of writing this loop?
I'm not sure if this is more Pythonic:
>>> word_frequency = {'dogs': [1234, 4321], 'are': [9999, 0000], 'fun': [4389, 3234]}
>>> vocab_frequency = [sum(x[0] for x in word_frequency.values()),
sum(x[1] for x in word_frequency.values())]
>>> print(vocab_frequency)
[15622, 7555]
Alternate solution with reduce
:
>>> reduce(lambda x, y: [x[0] + y[0], x[1] + y[1]], word_frequency.values())
[15622, 7555]
You could use numpy for that:
import numpy as np
word_frequency = {'dogs': [1234, 4321], 'are': [9999, 0000], 'fun': [4389, 3234]}
vocab_frequency = np.sum(list(word_frequency.values()), axis=0)
list(map(sum, zip(*word_frequency.values())))
Probably not the shortest way to solve this, but hopefully the most comprehensible...
word_frequency = {'dogs': [1234, 4321], 'are': [9999, 0000], 'fun': [4389, 3234]}
negative = (v[0] for v in word_frequency.values())
positive = (v[1] for v in word_frequency.values())
vocab_frequency = sum(negative), sum(positive)
print (vocab_frequency) # (15622, 7555)
Though more experienced Pythonistas might rather use zip to unpack the values:
negative, positive = zip(*word_frequency.values())
vocab_frequency = sum(negative), sum(positive)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With