Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 迭代给定起点的列表_Python_List_Loops_Indexing_Iteration - Fatal编程技术网

Python 迭代给定起点的列表

Python 迭代给定起点的列表,python,list,loops,indexing,iteration,Python,List,Loops,Indexing,Iteration,假设你有一个列表,并且给了你一个起点(例如第三个索引)。如何从该索引开始迭代列表,并循环访问列表中的所有元素?意思是,您可以在列表中间开始迭代,但一旦到达结束,就从开始一直到列表中的每个元素都已被访问。做这样的事情最干净、最有效的方法是什么?理想情况下,我希望在以I:开头的列表中为x寻找一些有效的python伪代码 为了返回(没有itertools),必须使用除法运算符的余数: i = start_index while i < len(mylist) + start_index:

假设你有一个列表,并且给了你一个起点(例如第三个索引)。如何从该索引开始迭代列表,并循环访问列表中的所有元素?意思是,您可以在列表中间开始迭代,但一旦到达结束,就从开始一直到列表中的每个元素都已被访问。做这样的事情最干净、最有效的方法是什么?理想情况下,我希望在以I:开头的列表中为x寻找一些有效的python伪代码

为了返回(没有itertools),必须使用除法运算符的余数:

i = start_index
while i < len(mylist) + start_index:
    print mylist[i % len(mylist)]
    i+=1
为了完整起见,并且由于在这种情况下生成器将更高效,正如@Régis B所建议的,您可以:

def mygen(lst, start):
    for idx in range(len(lst)):
        yield  lst[(idx + start) % len(lst)]

如果列表很大,并且希望避免复制部分列表,则需要使用自定义迭代器:

def starting_with(arr, start_index):
     # use xrange instead of range in python 2
     for i in range(start_index, len(arr)):
        yield arr[i]
     for i in range(start_index):
        yield arr[i]

for value in starting_with(my_list, 3):
    ...

您可以创建自己的迭代器函数,该函数可以非常方便(高效)地执行此操作,如下所示

需要注意的是,正如所写的,您可以向它传递一个负索引,列表的长度有效地添加到该索引中,因此
-2
将意味着列表中倒数第二个项目,这正是Python本身通常处理列表负索引的方式

try:
    xrange
except NameError:  # Python 3
    xrange = range

def starting_with(start_index, seq):
    if start_index > 0:
        start_index = start_index-len(seq)
    for i in xrange(start_index, len(seq)+start_index):
        yield seq[i]

for value in starting_with(3, my_list):
    ...

我倾向于对范围内的索引(len(mylist))使用
:打印mylist[(index+start\u index)%len(mylist)]
,而不是在
循环时使用
。@rll我怀疑它会因此被否决。。。可能是因为
i++
,您很快就将其删除了。
try:
    xrange
except NameError:  # Python 3
    xrange = range

def starting_with(start_index, seq):
    if start_index > 0:
        start_index = start_index-len(seq)
    for i in xrange(start_index, len(seq)+start_index):
        yield seq[i]

for value in starting_with(3, my_list):
    ...