Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python :function that takes an iterable argument and generates tuples

I try to do something on python.

I try to write a function that takes an iterable argument and generates tuples of 2 elements:

  1. the current iterable element
  2. the number of times it has been generated since the beginning

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

like image 280
bryan tetris Avatar asked Jan 21 '26 14:01

bryan tetris


2 Answers

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))
like image 129
Håken Lid Avatar answered Jan 23 '26 03:01

Håken Lid


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)]
like image 31
kabanus Avatar answered Jan 23 '26 02:01

kabanus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!