[英]python loop through list all the way back to element chosen
lets say i picked element 2 in a 4 element list. 可以说我在4个元素列表中选择了元素2。 How can i then loop through the whole list back to element 2. I have tried -1, -i, 1-i, i-1 but the list never goes back to element 0 just stops at the last one.
然后,我如何遍历整个列表回到元素2。我尝试过-1,-i,1-i,i-1,但是列表从未返回到元素0,只是在最后一个元素处停止。 eg
例如
rand_list = ["750", "500", "255", "1000"]`
for i in range(len(rand_list)):
print(rand_list[i:X])
in this what would i put in place of X i would want the print to be 750 500 255 1000
then 500 255 1000 750
then 255 1000 750 500
etc. 在这种情况下,我要代替X我希望打印为
750 500 255 1000
然后500 255 1000 750
然后255 1000 750 500
等。
Just slice the list twice and concatenate the results: 只需将列表切片两次,然后将结果连接起来:
>>> for i in range(len(rand_list)):
... print(rand_list[i:] + rand_list[:i])
...
['750', '500', '255', '1000']
['500', '255', '1000', '750']
['255', '1000', '750', '500']
['1000', '750', '500', '255']
This could work : Creating a list of index with the order you like. 这可能会起作用:创建具有所需顺序的索引列表。
rand_list = ["750", "500", "255", "1000"]
index = 2
for i in range(index, len(rand_list))+range(index) :
print "index : {}, value : {}".format(i, rand_list[i])
It will output : 它将输出:
index : 2, value : 255
index : 3, value : 1000
index : 0, value : 750
index : 1, value : 500
Also, if you want to test all cases, you can update index
with a loop from values of range(len(rand_list))
. 此外,如果要测试所有情况,则可以使用循环从
range(len(rand_list))
值更新index
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.