Question

I'm trying to count how times something occurs in a list. Is it possible to set a variable to move through each index and count it. I want to append how many times each one is counter to a list.
I want it to look like this. Forget the while loop, it's just to show that I'm looping this. example. And if possible to to import a library to make a shortcut, or if its the only way.

while True:
    index = 0
    L = ["brown", "brown", "brown", "red", "red", "yellow", "yellow"]
    numberOfTimes = L.count([index]) 
    index = index + numberOfTimes 
    numberOfTimesList.append(numberOfTimes)

I'd then want to make another list and so that I'd only see brown once like this:

["brown", "red", "yellow"] [3, 2, 2]

No correct solution

OTHER TIPS

Use collections.counter:

from collections import Counter
L = ["brown", "brown", "brown", "red", "red", "yellow", "yellow"]
cnt = Counter(L)
print cnt
print cnt.keys(), cnt.values()

Output:

Counter({'brown': 3, 'yellow': 2, 'red': 2})
['brown', 'yellow', 'red'] [3, 2, 2]

The resulting counter object can be manipulated as a dictionary, with additional convenient routines such as cnt.most_common(n) which will return the n most common elements and their counts.

You can easily do this:

[1, 2, 3, 4, 1, 4, 1].count(1)

The above code counts the number of times the number 1 appears in the list. You can do the same for your list.

In your case do this.

for thing in L:
  # Count variable represents the number of times the thing variable was found
  count = L.count(thing)

To the basic of Python:

First, a Pythonic way for loop or iteration is:

In [5]: L = ["brown", "brown", "brown", "red", "red", "yellow", "yellow"]

In [6]: for i in L:
   ...:     print i
   ...:     
brown
brown
brown
red
red
yellow
yellow

Second, to count the occurrence, the most basic and powerful tool in Python: dict will help.

In [8]: counts = {}

In [9]: for i in L:
   ...:     counts[i] = (counts[i] + 1) if (i in counts) else 1
   ...:     

In [10]: counts
Out[10]: {'brown': 3, 'red': 2, 'yellow': 2}

In [11]: counts.keys()
Out[11]: ['brown', 'yellow', 'red']

In [12]: counts.values()
Out[12]: [3, 2, 2]

Using collections.Counter as @YS-L said is more convince for your question, but I think it would be better to be familiar with basic of Python before useing a tool of higher level

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