[英]Get next item in list. At the end go back to the beginning
我想在列表中找到下一個元素。 在列表 go 的末尾開始並獲取索引為 0 的元素。
所以它在無限循環中運行。
my_list = [5, 1, 2, 7, 9, 10] # all values are unique
while True:
for item in my_list:
current_item = my_list[my_list.index(item)]
try:
next_item = my_list[my_list.index(item) + 1]
except IndexError:
next_item = my_list[0]
print (current_item, next_item)
可以在沒有嘗試/除外的情況下完成嗎?
如果你想重復遍歷一個列表,當你到達末尾時循環回到第一個項目,使用itertools.cycle()
。
如果你想永遠循環遍歷這些項目,你可以像這樣輕松地做到這一點:
mylist = [5, 1, 2, 7, 9, 10]
while True:
for (i,x) in enumerate(mylist):
ci = x
ni = mylist[(i+1)%len(mylist)]
print(ci,ni)
也可以這樣做
l = [5, 1, 2, 7, 9, 10]
curIndex = 0
l_len = len(l)
while True:
if curIndex >= l_len:
curIndex = curIndex - l_len
print(l[curIndex])
curIndex += 1```
是的。 例如,您可以使用len
來執行此操作,但 @ThePilotDude 是對的。
my_list = [5, 1, 2, 7, 9, 10]
while True:
for i in range(0, len(my_list)): # Loop 1 - length of my_list times
current_item = my_list[i]
if i + 1 < len(my_list):
next_item = my_list[i + 1]
else:
print(current_item, my_list[0])
break
print(current_item, next_item)
與你所擁有的相似。
這是一個簡單的解決方案:
my_list = [5, 1, 2, 7, 9, 10]
while True:
for index,current in enumerate(my_list):
next_index = (index+1)%len(my_list)
next_item=my_list[next_index]
print (current, next_item)
my_list = [5, 1, 2, 7, 9, 10]
for item in range(len(my_list)):
if(item == len(my_list) - 1):
break
current_item = my_list[item]
next_item = my_list[item+1]
print (current_item, next_item)
由於 while 循環,它會繼續無限次。 它可以是這樣的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.