November 8th, 2012, 08:42 PM
Question about lists
Hi, what could I do if I wanted to find out how many times a certain value appeared in a list. For example how could I find out how many times "Z" appeared in list 1
November 8th, 2012, 10:16 PM
This counts the occurrences of every value in the list, assuming each value is hashable. If you only care about one value, I think you're better off manually comparing each list item to the value and incrementing a counter when equality occurs.
>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> a = ['a', 'b', 'c', 'a', 'b', 'd']
>>> for x in a:
... d[x] += 1
November 8th, 2012, 10:31 PM
I'd use the interpreter. Browsing through the output of
I'd find a count method. And then I'd learn more detail:
And maybe I'd look in the iterables or list section of the module library reference at docs.python.org .
And I'd practice with a few cases back in the interpreter to make sure the funny variations I can think of work in reasonable ways.
And then I'd be ready to use the list.count method.
Comments on this post
[/code] are essential for python code and Makefiles!
November 9th, 2012, 06:55 PM
November 9th, 2012, 08:36 PM
Here's an example of what b49P23TIvg was referring to:
>>> for i in range (0,a.count('A')):
... e = a.index('A',i)
... print ("element ",e," is the letter ",a[e])
element 0 is the letter A
element 2 is the letter A