Reputation: 31
My code looks like this, where words
is a list:
for a in words:
if a in animals:
ani += 1
elif a in nature:
nat += 1
elif a in objects:
obj += 1
...and so on. I have about 30 different categories I'm trying to arrange the words
into.
How I can I write this more concisely?
Upvotes: 0
Views: 68
Reputation: 164693
I suggest you split your logic into 2 steps. First, reverse your category mappings to map animals to category. For example:
animals = {'elephant', 'cobra', 'tiger', 'cow', 'mouse', 'fish', 'turtle'}
objects = {'door', 'house', 'desk'}
d_cats = {'animals': animals, 'objects': objects}
d_cats_rev = {w: k for k, v in d_cats.items() for w in v}
You may find the above verbose and painful. But, really, you should never have to make 30 related variables. You should store them in a dictionary for ease, readability, and performance.
Second, use collections.Counter
, utilizing the mapping you have just created:
from collections import Counter
res = Counter(map(d_cats_rev.get, words))
Again, the beauty of this method is that you aren't creating new variables, but holding the result in an easily accessible and transportable dictionary.
If you find you haven't mapped all words, and only want to include ones you have mapped, you can use filter
to remove them:
res = Counter(filter(None, map(d_cats_rev.get, words)))
Upvotes: 3