I try to do something on python.
I try to write a function that takes an iterable argument and generates tuples of 2 elements:
Here is my code
liste = ['a','b','a','a','b']
compte = {}.fromkeys(set(liste),0)
for valeur in liste:
compte[valeur] += 1
print(compte)
output :
{'b': 2, 'a': 3}
But I want to obtain "a:1" "b:1" "a:2" "a:3" and "b:2"
Thanks for help
Use a generator function.
from collections import defaultdict
def with_running_count(values):
counts = defaultdict(int)
for value in values:
counts[value] += 1
yield value, counts[value]
>>> print(*with_running_count('abaab'))
('a', 1) ('b', 1) ('a', 2) ('a', 3) ('b', 2)
One advantage of using a generator over the other suggestions is that generators are lazy. That means that you can pass in iterators that return an endless (or very large) data stream, since the generator only consumes the input stream when needed.
# an endless iterator
coin = iter(lambda: random.choice(['heads', 'tails']), None)
# the running count will also be endless
toss = with_running_count(coin)
>>> next(toss), next(toss), next(toss)
(('tails', 1), ('tails', 2), ('heads', 1))
Your expected result is a list, not a dictionary. A fix to your code would be to use your dict for counting, but appending to a list:
>>> liste = ['a','b','a','a','b']
>>>
>>> compte = dict.fromkeys(liste,0) #Or use a default dict
>>> result = []
>>> for valeur in liste:
... compte[valeur] += 1
... result.append((valeur,compte[valeur]))
...
>>> print(result)
[('a', 1), ('b', 1), ('a', 2), ('a', 3), ('b', 2)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With