简体   繁体   English

遍历python中的两个列表

[英]Iterate through two lists in python

I have two different lists, one has a set of days (70) and the other has 3 names.我有两个不同的列表,一个有一组天数 (70),另一个有 3 个名字。 I would like to assign a name to every 7 days, and thought this was the way to do so, but now it only assigns one name to every date.我想每 7 天指定一个名称,并认为这是这样做的方式,但现在它只为每个日期指定一个名称。

date_list is a list of 70 days and names contains 3 different names. date_list 是 70 天的列表,名称包含 3 个不同的名称。

How can I fix this?我怎样才能解决这个问题?

    date_dict = {}
    sum_names = len(names)
    counter = 0

for date in date_list:
                # If counter is sum of names, reset counter to 0
                if (counter == sum_names):
                        counter = 0

                # Else increment counter and add dictionary key/value        
                else:
                        date_dict[date] = names[counter]
                        counter += 1


print(date_dict)

If you take your list of three names and turn it into a list of 3x7 names, you can just cycle over it.如果你把你的三个名字列表变成一个 3x7 名字的列表,你可以循环它。

So starting with:所以从:

names = ['Donald', 'Ricky', 'Morty']

# Three * 7 names:
groups = [word for entry in names for word in [entry]*7]
# ['Donald','Donald','Donald',...'Ricky', 'Ricky', ... 'Morty']

With that you can just zip the cycle and dates:有了它,您只需 zip 周期和日期:

from datetime import datetime, timedelta
from itertools import cycle

# a list of 70 dates
today = datetime.today()
date_list = [(today + timedelta(days=x)).strftime('%Y-%m-%d') for x in range(70)]

names = ['Donald', 'Ricky', 'Morty']
groups = [word for entry in names for word in [entry]*7]

# zip with cycle for a dict (or any other structure you want):
{date: name for date, name in zip(date_list, cycle(groups))}

Which will give you:这会给你:

{'2022-02-15': 'Donald',
 '2022-02-16': 'Donald',
 '2022-02-17': 'Donald',
 '2022-02-18': 'Donald',
 '2022-02-19': 'Donald',
 '2022-02-20': 'Donald',
 '2022-02-21': 'Donald',
 '2022-02-22': 'Ricky',
 '2022-02-23': 'Ricky',
 '2022-02-24': 'Ricky',
 '2022-02-25': 'Ricky',
 ...
 '2022-04-17': 'Morty',
 '2022-04-18': 'Morty',
 '2022-04-19': 'Donald',
 '2022-04-20': 'Donald',
 '2022-04-21': 'Donald',
 '2022-04-22': 'Donald',
 '2022-04-23': 'Donald',
 '2022-04-24': 'Donald',
 '2022-04-25': 'Donald'}

By using extended slicing you can split your list into every nth interval (ie every seventh day).通过使用扩展切片,您可以将列表分成每第 n 个间隔(即每第七天)。

In your case this can be done in the following way:在您的情况下,这可以通过以下方式完成:

every_seventh_day = date_list[::7]
>> [day0, day7, day14, etc..]

You can then adjust your code in the following way:然后,您可以按以下方式调整代码:

for date in every_seventh_day:
                # If counter is sum of names, reset counter to 0
                if (counter == sum_names):
                        counter = 0

                date_dict[date] = names[counter]
                counter += 1

ps.附言。 The current implementation of the else statement will skip the iteration of counter=0 and names[0] will never be assigned a date. else语句的当前实现将跳过 counter=0 的迭代,并且 names[0] 永远不会被分配日期。 - unless this is intended for your use case it should be safe to remove:) - 除非这是针对您的用例,否则删除它应该是安全的:)

You can read more about slicing from the docs, specifically this example.您可以从文档中阅读更多关于切片的信息,特别是这个例子。 https://python-reference.readthedocs.io/en/latest/docs/brackets/slicing.html#example-3 https://python-reference.readthedocs.io/en/latest/docs/brackets/slicing.html#example-3

Edit: Solution 2 : The following solution Loops through each day progressively reducing the date_list size until empty,编辑:解决方案 2 :以下解决方案每天循环逐步减少date_list大小直到为空,

In each iteration it updates date_dict with the next 7 days from the date_list as keys and with the name[counter] as the value.在每次迭代中,它使用date_dict中接下来的 7 天作为键并使用name[counter]作为值来更新date_list

It then increments the name counter value and checks if it needs to be reset.然后它会增加名称计数器的值并检查它是否需要重置。 Additionally also checks if there are seven days for the next person else give them the remainder.此外还检查下一个人是否有 7 天的时间给他们剩下的时间。

date_dict = {}
date_list= ["2022-02-16", "2022-02-17", "2022-02-18", etc..]
names = ["Donald", "Rick"]
counter = 0

while len(date_list) > 0:
    date_dict.update(dict.fromkeys([date_list.pop(0) for _ in range(7)], names[counter]))
    counter +=1
    if counter == len(names):
        counter = 0
    # Safety check if the list doesnt have at least 7 dates for the next iteration
    if len(date_list) < 7:
        date_dict.update(dict.fromkeys([date_list.pop(0) for _ in range(len(date_list))], names[counter]))

Having two counters for keeping track of the dates and names should work.有两个用于跟踪日期和名称的计数器应该可以工作。

    date_dict = {}
    sum_names = len(names)
    date_len = 7
    date_counter = 0
    name_counter = 0

for date in date_list:
                # If date counter has hit 7 days then reset date counter and increment name_counter
                if (date_counter == date_len):
                        date_counter = 0
                        #if the name_counter has hit the sum of names then reset else increment
                        if(name_counter == sum_names):
                          name_counter=0
                        else:
                          name_counter+=1

                # Else increment counter and add dictionary key/value        
                else:
                        date_dict[date] = names[name_counter]
                        date_counter += 1

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

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