Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip variable number of iterations in Python for loop

I have a list and a for loop such as these:

mylist = ['foo','foo','foo','bar,'bar','hello']
for item in mylist:
    cp = mylist.count(item)
    print("You "+item+" are present in "+str(cp)+" copy(ies)")

Output:

You foo are present in 3 copy(ies)
You foo are present in 3 copy(ies)
You foo are present in 3 copy(ies)
You bar are present in 2 copy(ies)
You bar are present in 2 copy(ies)
You dude are present in 1 copy(ies)

Expected output:

You foo are present in 3 copy(ies)
You bar are present in 2 copy(ies)
You dude are present in 1 copy(ies)

The idea is thus to skip a variable number of iterations within the for loop, using something like this script (not working):

for item in mylist:
    cp = mylist.count(item)
    print("You "+item+" are present in "+str(cp)+" copy(ies)")
    continue(cp)

The script would thus "jump" cp elements in the for loop at every round and start doing again what it is asked at the item item + cp.

I know that you can use continue to skip multiple iterations (such as in this post) but I cannot figure out how to use continue to skip a variable number of iterations.

Thanks for your answer! :)


Edit: similar items are always next to each other.

like image 240
tlorin Avatar asked Mar 25 '26 16:03

tlorin


2 Answers

You could use a Counter:

from collections import Counter

mylist = ['foo','foo','foo','bar','bar','hello']
c = Counter(mylist)
for item, cp in c.items():
    print("You "+item+" are present in "+str(cp)+" copy(ies)")
like image 127
Tom Dalton Avatar answered Mar 28 '26 04:03

Tom Dalton


You can use collections.Counter for your job:

>>> from collections import Counter
>>> Counter(['foo', 'foo', 'bar'])
Counter({'foo': 2, 'bar': 1})

Thus,

count_dict = Counter(mylist)
for item in count_dict:
    print("You "+item+" are present in "+str(count_dict[item[)+" copy(ies)")
like image 33
Aswin Murugesh Avatar answered Mar 28 '26 04:03

Aswin Murugesh



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!