I am fairly new to python, but I haven't been able to find a solution to my problem anywhere. Show I want to count the occurrences of a string inside a list of tuples. Here is the list of tuples:
I've tried this but it just prints 0
As the same ID occurs twice in the list, this should return:
I also tried to increment a counter for each occurrence of the same ID but couldn't quite grasp how to write it. *EDIT: Using Eumiro's awesome answer. I just realized that I didn't explain the whole problem. I actually need the total amount of entries which has a value more than 1. But if I try doing:
I get this error:
Cœur 35.6k24 gold badges188 silver badges257 bronze badges asked Apr 15, 2013 at 10:59
Maybe
returns
It is fast since it iterates over your list just once. You iterate over entries and then try to get a count of these entries within your list. That cannot be done with
But
seriously, have a look at EDIT: I actually need the total amount of entries which has a value more than 1. You can still use the
returns
answered Apr 15, 2013 at 11:01
eumiroeumiro 198k33 gold badges294 silver badges259 bronze badges 6
@eurmiro's answer shows you how to do it with
answered Apr 15, 2013 at 11:11
jamylakjamylak 124k29 gold badges227 silver badges227 bronze badges 0 I needed some extra functionality that Counter didn't have. I have a list of tuples that the first element is the key and the second element is the amount to add. @jamylak solution was a great adaptation for this!
answered Jan 24, 2019 at 6:49
How do I find a number in a tuple?Find the index of an element in tuple using index()
Tuple provides a member function index() i.e. It returns the index for first occurrence of x in the tuple. Also, if element is not found in tuple then it will throw an exception ValueError.
How do you count items in Python?The most straightforward way to get the number of elements in a list is to use the Python built-in function len() . As the name function suggests, len() returns the length of the list, regardless of the types of elements in it.
How do you count certain elements in a list Python?The count() is a built-in function in Python. It will return you the count of a given element in a list or a string. In the case of a list, the element to be counted needs to be given to the count() function, and it will return the count of the element. The count() method returns an integer value.
Which function returns the number of elements in the tuple?The len() method returns the number of elements in the tuple.
|