Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Associate for loop with a list

I couldn't find any workaround for this. In my real example this will serve to associate color masks with objects.

I think the best way to explain is give an example:

objects = ['pencil','pen','keyboard','table','phone']
colors  = ['red','green','blue']

for n, i in enumerate(objects):
    print n,i #0 pencil

    # print the index of colors

The result I need:

#0 pencil    # 0 red
#1 pen       # 1 green
#2 keyboard  # 2 blue
#3 table     # 0 red
#4 phone     # 1 green

So, there will be always 3 colors to associate with the objects, How can I get this result within a for loop in python? Every time the n (iterator) is bigger than the length of the colors list, how can I tell it to go back and print the first index and so on?

like image 650
user1765661 Avatar asked Dec 01 '25 05:12

user1765661


2 Answers

Use %:

for n, obj in enumerate(objects):
    print n, obj, colors[n % len(colors)]

or zip() and itertools.cycle():

from itertools import cycle

for n, (obj, color) in enumerate(zip(objects, cycle(colors))):
    print n, obj, color

Demo:

>>> objects = ['pencil','pen','keyboard','table','phone']
>>> colors  = ['red','green','blue']
>>> for n, obj in enumerate(objects):
...     print n, obj, colors[n % len(colors)]
... 
0 pencil red
1 pen green
2 keyboard blue
3 table red
4 phone green
>>> from itertools import cycle
>>> for n, (obj, color) in enumerate(zip(objects, cycle(colors))):
...     print n, obj, color
... 
0 pencil red
1 pen green
2 keyboard blue
3 table red
4 phone green
like image 81
Martijn Pieters Avatar answered Dec 03 '25 20:12

Martijn Pieters


>>> from itertools import count, izip, cycle
>>> objects = ['pencil','pen','keyboard','table','phone']
>>> colors  = ['red','green','blue']
>>> for i, obj, color in izip(count(), objects, cycle(colors)):
...     print i, obj, color
... 
0 pencil red
1 pen green
2 keyboard blue
3 table red
4 phone green

or

>>> for i, obj, j, color in izip(count(), objects, cycle(range(len(colors))), cycle(colors)):
...     print i, obj, j, color
... 
0 pencil 0 red
1 pen 1 green
2 keyboard 2 blue
3 table 0 red
4 phone 1 green
like image 38
koffein Avatar answered Dec 03 '25 18:12

koffein



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!