如果迭代不是从第一个元素开始,那么如何通过for循环传递列表中的所有项目

时间:2012-05-11 17:26:19

标签: language-agnostic iteration

如何通过for循环传递列表中的所有项目。如果迭代不是从第一个元素开始的。

让我们马上跳到榜样:

我们有列表 ['a','b','c','d']

我想使用for循环遍历此列表中的所有项目。但是如果迭代不是从第一个元素开始,我想从第一个元素开始返回oand。 这样的事情:

lst = ['a','b','c','d']

start_index = 2

for loop_num in range(len(lst)):
    item = lst[start_index+loop_num]
    print item

它会打印我:

>> c,d

比上升 IndexOutOfRange错误

但我希望结果如下:

>> c, d, a, b

如果我们将start_index变量更改为1,则结果假设为:

b, c, d, a
start_index = 0

的情况下

结果: a, b, c, d

5 个答案:

答案 0 :(得分:5)

lst = ['a','b','c','d']

start_index = 2

for loop_num in range(len(lst)):
    item = lst[(start_index+loop_num) % len(lst)]
    print item

% - 这是特殊操作。 3%5 = 3,10%5 = 0, 阅读RemainderPython Doc

答案 1 :(得分:4)

的Python

>>> l = ['a','b','c','d']
>>> def func(lst, idx=0):
...     for i in lst[idx:] + lst[:idx]: yield i
...
>>> list(func(l))
['a', 'b', 'c', 'd']
>>> list(func(l,2))
['c', 'd', 'a', 'b']
>>>

使用标准的Python列表切片语法,一个可选参数(idx)和a generator

答案 2 :(得分:2)

您可以使用%来获取正确的索引:

def rotated(lst, start=0):
    c = len(lst)
    for idx in xrange(c):
        yield lst[(idx + start) % c]


for x in rotated(['a','b','c','d'], 2):
    print x,

答案 3 :(得分:2)

我将在C#中回答。假设我们有一个大小为x的数组(更容易显示)。起始索引是y,小于x,但大于0。

int i;
for(i=y;i<x;i++)
{
  //do something with MyArray[i]¸
  if(i==x)
  {
    for(i=0;i<y;i++)
    {
      //do something with MyArray[i]
    }
    i=x;
  }
}

答案 4 :(得分:1)

在Ruby数组中有一个名为values_at的方法,它接受一个索引或一系列索引(以任意数量组合)。很少使用for循环 - 这是我写的第一个。

lst = ['a','b','c','d']
start_index = 2

for v in lst.values_at(start_index..-1, 0...start_index)
  puts v
end