简体   繁体   中英

Cycle through multiple lists with enumerate?

I'm currently assigning each person in a list to a specific week of the month. This is done for the the entire year.

import itertools
import datetime

today = datetime.date.today()
today_str = str(today)
year,month,date = today_str.split('-')
# convert week of the year to a number
current_week = (datetime.date(int(year), int(month), int(date)).isocalendar()[1])

name_list1 = ["Kacey", "Cindy", "John"]

for num, item in enumerate(itertools.cycle(name_list1), 7):
    if num >= current_week:
        print(item)
        break

The above will find the person that falls on the 7th week.... Kacey

1. Kacey
2. Cindy
3. John
4. Kacey
5. Cindy
6. John
7. Kacey

How can I do this with 2 lists of names? So each name in list1 will be assigned a week and each name in list2 will be assigned a week? They are totally independent of each other. I'm wanting to do this in one for loop if possible.

name_list1 = ["Kacey", "Cindy", "John"]
name_list2 = ["Bob", "Julie", "Brian"]

In list2, Bob would be #7.

1. Bob
2. Julie
3. Brian
4. Bob
5. Julie
6. Brian
7. Bob

I could create a for loop for each list, but that will get rather ugly when dealing with multiple lists.

I was able to zip it:

for num, (item1, item2) in enumerate(itertools.cycle(zip(name_list1, name_list2)), 7):
    if num >= current_week:
        print(item1 + " " + item2)
        break

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM