Python|列表中的索引特定循环迭代
循环迭代的问题很常见,但有时,我们会遇到这样的问题,即我们需要以循环迭代的方式处理列表,也就是从特定索引开始。让我们讨论一些可以解决这个问题的方法。
方法 #1:使用%
运算符+ 循环
%运算符可用于循环超出范围的索引值以从列表的开头开始以形成循环,从而有助于循环迭代。
# Python3 code to demonstrate
# cyclic iteration in list
# using % operator and loop
# initializing tuple list
test_list = [5, 4, 2, 3, 7]
# printing original list
print ("The original list is : " + str(test_list))
# starting index
K = 3
# using % operator and loop
# cyclic iteration in list
res = []
for i in range(len(test_list)):
res.append(test_list[K % len(test_list)])
K = K + 1
# printing result
print ("The cycled list is : " + str(res))
输出:
The original list is : [5, 4, 2, 3, 7]
The cycled list is : [3, 7, 5, 4, 2]
方法#2:使用itertools.cycle() + itertools.islice() + itertools.dropwhile()
itertools 库内置了可以帮助解决这个特定问题的函数。 cycle函数执行循环部分,dropwhile函数将循环带到列表的开头,islice函数指定循环大小。
# Python3 code to demonstrate
# cyclic iteration in list using itertools
from itertools import cycle, islice, dropwhile
# initializing tuple list
test_list = [5, 4, 2, 3, 7]
# printing original list
print ("The original list is : " + str(test_list))
# starting index
K = 3
# using itertools methods for
# cyclic iteration in list
cycling = cycle(test_list)
skipping = dropwhile(lambda x: x != K, cycling)
slicing = islice(skipping, None, len(test_list))
slicing = list(slicing)
# printing result
print ("The cycled list is : " + str(slicing))
输出:
The original list is : [5, 4, 2, 3, 7]
The cycled list is : [3, 7, 5, 4, 2]