如何在指定起始索引时无限遍历列表?

时间:2017-01-24 19:24:26

标签: python python-2.7 iteration

我有一个名为all_urls的列表。我试图无限地遍历列表。我有一个索引i,我想从它开始。例如:

  

www.google.com

     

www.facebook.com

     

www.linkednin.com

     

www.yahoo.com

     

www.microsoft.com

我想从linkedin开始迭代然后进入无限循环。

我试过看过这个链接:

How can I infinitely loop an iterator in Python, via a generator or other?

但是这个链接没有说明我如何从某个中间点开始。

我试过了

    for url in itertools.cycle(all_urls[i:]):
        print "Process URL : " + url

但它不起作用。

1 个答案:

答案 0 :(得分:2)

你有几个选择。也许最简单的选择是建立一个新的循环列表:

urls = all_urls[i:] + all_urls[:i]
for url in itertools.cycle(urls):
   print(url)

我建议的第二个解决方案就是消耗周期的第一个i - 1元素:

# From https://docs.python.org/2/library/itertools.html#recipes
def consume(iterator, n):
    "Advance the iterator n-steps ahead. If n is none, consume entirely."
    # Use functions that consume iterators at C speed.
    if n is None:
        # feed the entire iterator into a zero-length deque
        collections.deque(iterator, maxlen=0)
    else:
        # advance to the empty slice starting at position n
        next(itertools.islice(iterator, n, n), None)

urls = itertools.cycle(all_urls)
consume(urls, i - 1)
for url in urls:
    print(url)