To create a Python counter from a list of tuples, you can use the collections
module and the Counter
class. Here’s an example:
from collections import Counter
my_list = [('apple', 3), ('banana', 2), ('orange', 1), ('apple', 2), ('banana', 1)]
# Create a counter from the list of tuples
my_counter = Counter(dict(my_list))
print(my_counter) # Output: Counter({'apple': 5, 'banana': 3, 'orange': 1})
In this example, we define a list of tuples my_list
where each tuple contains a value and its count. We then use the dict()
constructor to convert the list of tuples into a dictionary, and pass the dictionary to the Counter()
constructor to create a counter object.
The resulting my_counter
object contains a count of each unique value in the list of tuples.
Alternatively, you can use the update()
method of the Counter
class to add each tuple to the counter:
from collections import Counter
my_list = [('apple', 3), ('banana', 2), ('orange', 1), ('apple', 2), ('banana', 1)]
# Create an empty counter
my_counter = Counter()
# Update the counter with each tuple
for tup in my_list:
my_counter[tup[0]] += tup[1]
print(my_counter) # Output: Counter({'apple': 5, 'banana': 3, 'orange': 1})
In this example, we create an empty counter object my_counter
and use a for
loop to add each tuple to the counter using the update()
method.
Either method should work for creating a counter from a list of tuples in Python.
+ There are no comments
Add yours