简体   繁体   English

使用枚举循环遍历多个列表?

[英]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以上将找到落在第7周的人...... 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?我怎样才能用 2 个名字列表来做到这一点? So each name in list1 will be assigned a week and each name in list2 will be assigned a week?那么 list1 中的每个名字都会被分配一个星期,而 list2 中的每个名字都会被分配一个星期? They are totally independent of each other.它们彼此完全独立。 I'm wanting to do this in one for loop if possible.如果可能,我想在一个 for 循环中执行此操作。

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

In list2, Bob would be #7.在列表 2 中,Bob 将是 #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.我可以为每个列表创建一个 for 循环,但是在处理多个列表时会变得很丑陋。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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