在列表上进行迭代,起点有所偏移

时间:2018-10-03 10:39:47

标签: python python-3.x list iteration

使用Python3,我需要从任意i(i <= 6)开始依次遍历元素列表,完成整个迭代周期,从i + = 1开始重复它,依此类推。此循环不应结束。在内容上,这是从当前日期开始的星期几名称的获取。例如,如果今天是星期三,则由于迭代,我必须获得一个列表[星期三,星期四,星期五,星期六,星期日,星期一,星期二]。这似乎很简单,但我处于死胡同。我会很感谢您的提示或帮助。

4 个答案:

答案 0 :(得分:1)

您可以使用itertools.chainitertools.cycle获得产生所需序列的无限迭代:

from itertools import chain, cycle

for x in chain(the_list[i:], cycle(the_list)):
    print(x)

用作:

>>> from itertools import chain, cycle
>>> the_list = range(10)
>>> i = 6
>>> for x in chain(the_list[i:], cycle(the_list)):
...     print(x)
6
7
8
9
0
1
2
3
4
5
6
7
8
9
0
[... forever ...]

等效使用cycle + islice

>>> for x in islice(cycle(the_list), i, None):
...     print(x)
>>> for x in islice(cycle(the_list), i, 20):
...     print(x)
... 
6
7
8
9
0
1
2
3
4
5
6
7
8
9
0
[... forever ...]

答案 1 :(得分:0)

通常可以在以下循环场景中充分利用模运算符%

days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

i = 2  # Wednesday

while True:
    print(days[i])
    i += 1
    i = i % len(days)  # 7 => 0

Wednesday
Thursday
Friday
Saturday
Sunday
Monday
Tuesday
Wednesday
...

答案 2 :(得分:0)

如果我理解正确,那么您正在尝试在任何给定的日子里获得工作日 您可以传递工作日名称,并以相同的轮换顺序获得列表。 请看一下:-

from collections import deque
def rotate_week(week_days):
    a = deque(["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"])
    d = {}
    for i in range(len(a)):
        d[a[i]] = i
    number_to_rotate = d.get(week_days)
    a.rotate(-number_to_rotate)
    print(list(a))
rotate_week('Wednesday')

输出为:-

['Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday']

答案 3 :(得分:0)

from itertools import chain, dropwhile, repeat


def endless_daynames(starting_day):
    daynames = [
        'Monday', 'Tuesday', 'Wednesday', 'Thursday', 
        'Friday', 'Saturday', 'Sunday']
    # get starting day name 
    starting_day_name = daynames[starting_day] 
    # creating an endless iterable from an origin list
    endless_list = chain.from_iterable(repeat(daynames))
    # drop first items before we meet a required one
    shifted_list = dropwhile(lambda x: x != starting_day_name, endless_list)
    # yield values from it
    yield from shifted_list