0

I have the following code which runs through a list of words and increments variables representing colors as follows:

  white = 0
  gold = 0
  silver = 0
  grey = 0
  lavender = 0
  pink = 0
  red = 0
  green = 0
  blue = 0
  #list of colors
  colors = ['white','gold','silver','grey','lavender','pink','red','green','blue']
  #increment color variables accordingly
  for i in wordList:
    if colors[0] in i:
      white+=1
    if colors[1] in i:
      gold+=1
    if colors[2] in i:
      silver+=1
    if colors[3] in i:
      grey+=1
    if colors[4] in i:
      lavender+=1
    if colors[5] in i:
      pink+=1
    if i == colors[6]:
      red+=1
    if colors[7] in i:
      green+=1
    if colors[8] in i:
      blue+=1

I feel like there must be a better way to do this, but I'm not sure what it is. Thanks.

1
  • 2
    Hold the variables whose names are colours in a dict: {'white': 0, 'gold': 0, ...}. Then use a second for loop to check each key in the list and increment the value by 1. Commented Jun 7, 2019 at 15:42

3 Answers 3

1

I think that what you are looking for is Counter. which returns a dictionary with the name and number occurrences

from collections import Counter
d = Counter(wordList)

Now d will have what you are looking for and you can iterate over it doing d.items() or just d.values()

Sign up to request clarification or add additional context in comments.

Comments

1

Python contains the best datastructure for this issue called Counter

import collections
colors = ['white','gold','silver','grey','lavender','pink','red','green','blue']
counter = collections.Counter(colors)
print(counter)

The result

Counter({'white': 1, 'gold': 1, 'silver': 1, 'grey': 1, 'lavender': 1, 'pink': 1, 'red': 1, 'green': 1, 'blue': 1})

And you may access to the elements by names

> counter['white']
1

Comments

0

You can use defaultdicts for it:

from collections import defaultdict
colors_dict = defaultdict(int)
colors = ['white','gold','silver','grey','lavender','pink','red','green','blue']
wordList = ['lavender','gold','silver','waka','lavender','lavender']
for word in wordList:
    if word in colors:
        colors_dict[word] += 1
print(colors_dict)

defaultdict(<class 'int'>, {'silver': 1, 'lavender': 3, 'gold': 1})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.