所以我有这个清单
station_list = [1, 2, 3, 4]
这是一个例子,真正的列表可能更长,但总是这个模式增加整数。作为我的代码的一部分,如果满足某些条件,我想在不同于1的点访问该列表。
让我们说我想开始迭代2.我怎么能用for-loop
从2开始迭代列表,但仍然只获得所有元素一次?
因此,迭代顺序应为2, 3, 4, 1
。
答案 0 :(得分:5)
你可以这样做:
station_list = [1, 2, 3, 4]
start = 1 # item = 2 is at index position 1!
for item in (station_list[start:] + station_list[:start]):
# your code here
此输出:
[2, 3, 4, 1]
您可以在python here
中了解有关切片的更多信息如果你想在Python中获得关于列表的一些额外信息,this可能会有帮助。
答案 1 :(得分:4)
简单方法:使用原始列表中的两个块构建重新排序的列表:
station_list = [1, 2, 3, 4]
start = 1
for i in station_list[start:] + station_list[:start]:
print (i)
如果您不想构建重新排序的电台列表,则可以改为使用索引包装:
station_list = [1, 2, 3, 4]
start = 1
n = len(station_list)
for i in range(n):
print (station_list[(i+start)%n])
答案 2 :(得分:3)
这可以通过简单的collections.deque实现,然后使用任何索引旋转。
<DockPanel>
<Grid Name="gridStatusBar" Height="30" DockPanel.Dock="Bottom" Margin="0,0,0,0">
<StatusBar>
<StatusBarItem HorizontalAlignment="Left">
<Label
FontSize="13"
FontFamily="Comic Sans MS"
Foreground="Gainsboro"
Margin="0,-3,0,0"/>
</StatusBarItem>
</StatusBar>
</Grid>
<Grid Name="mainGrid">
<Grid.RowDefinitions>
<RowDefinition Height="270" />
<RowDefinition Height="200" />
<RowDefinition Height="260" />
</Grid.RowDefinitions>
</Grid>
</DockPanel>
输出:
from collections import deque
d = deque([1, 2, 3, 4])
d.rotate(-1)
print (d)
答案 3 :(得分:1)
station_list = [1, 2, 3, 4]
element_to_find = 2
start = station_list.index(element_to_find) - len(station_list)
for index in range(start, station_list.index(element_to_find)):
print(station_list[index])
答案 4 :(得分:0)
首先,将看到的列表定义为# !
所在的位置。 (也就是说,在定义列表之后。)
int_list = [1, 2, 3, 4, 5, 6]
seen = [] # {1}
然后,定义你的开始。
start = 2
这是循环部分。
for n in range(start, list_length): # starts at position you desire...
print(int_list[n])
seen.append(int_list[n])
如果你从一个不等于开头的位置开始,这会再次循环......
if int_list != seen: # if there are still some ints at start, go redo the loop until a seen int is found
for x in range(0, list_length):
print(int_list[x])
seen.append(int_list[x])
if int_list[x+1] in seen:
break
整个代码:
int_list = [1, 2, 3, 4, 5, 6]
seen = []
start = 2
list_length = len(int_list)
for n in range(start, list_length): # starts at position you desire...
print(int_list[n])
seen.append(int_list[n])
if int_list != seen:
# if there are still some ints at start, go redo the
#loop until a seen int is found
for x in range(0, list_length):
print(int_list[x])
seen.append(int_list[x])
if int_list[x+1] in seen:
break
不那么紧凑,但它确实有效。