我想将一个列表从START切换到STOP,但迭代继续经过最后一个元素,并一直循环回到第一个元素。然后继续踩到STOP。
我尝试了像这样的列表切片:
list_a = list(range(8))
reordered_list = list_a[5:2]
但只收到一个空列表:
[]
理想情况下,我希望 list_a 打印出来:
[5, 6, 7, 0, 1]
基本上,我希望遍历“完整循环”并继续在索引0处进行迭代。
答案 0 :(得分:2)
def parse(input, start, stop):
partial_list = input[:stop]
return partial_list[start:] + partial_list[:start]
full_list = range(8)
parse(full_list, 2, 5) # Outputs [2, 3, 4, 0, 1]
编辑:您的问题存在一些不一致之处,如果可能请重新编写。
答案 1 :(得分:1)
当您给出像 -
这样的切片索引时list_a[5:2]
这将需要1步,并且由于开始是在停止之后,这些索引之间没有元素(切片不会自行循环)。
您应该使用modulus
(余数)运算符和for循环或列表推导来获取所需的列表。示例 -
def foo(list_a, start, stop):
if start >= len(list_a):
start = len(list_a) - 1
if stop >= len(list_a):
stop = len(list_a) - 1
i = start
ret = []
while i != stop:
ret.append(list_a[i])
i = (i+1)%len(list_a)
return ret
示例/演示 -
>>> def foo(list_a, start, stop):
... if start >= len(list_a):
... start = len(list_a) - 1
... if stop >= len(list_a):
... stop = len(list_a) - 1
... i = start
... ret = []
... while i != stop:
... ret.append(list_a[i])
... i = (i+1)%len(list_a)
... return ret
...
>>> foo(list(range(8)),5,2)
[5, 6, 7, 0, 1]
答案 2 :(得分:1)
这样做:
def foo(list_a, start, stop):
if (start <= stop):
return list_a[start:stop]
else:
return list_a[start:] + list_a[:stop]
输出:
>>> x = list(range(8))
>>> foo(x, 5, 2)
[5, 6, 7, 0, 1]
答案 3 :(得分:0)
使用模数运算符%
:
>>> l = list(range(8))
>>> start = 5
>>> while start%len(l) != 2:
... print(l[start%len(l)])
... start += 1
...
5
6
7
0
1
作为一项功能:
>>> def foo(l, start, end):
... result = []
... while start%len(l) != end:
... result.append(l[start%len(l)])
... start += 1
... return result
...
>>> foo(l, 5, 2)
[5, 6, 7, 0, 1]
答案 4 :(得分:0)
这对我有用:
>>> reordered = (list_a[5:]+list_a[:2])
>>> print (reordered)
>>> [5, 6, 7, 0, 1]
基本上切片然后将它们加在一起。