简体   繁体   English

python遍历列表一直回到选择的元素

[英]python loop through list all the way back to element chosen

loop a list past the last element back to the first 将列表从最后一个元素循环回到第一个

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.

相关问题 有没有办法循环遍历python中的列表? - Is there a way to loop through a list in python? 有没有办法遍历 python 中的 for 循环中的列表? - Is there a way to loop through a list which is in a for loop in python? 此 for 循环不会遍历列表中的所有元素 - This for loop does not iterate through all element in a list Python:有没有办法从一个特定的索引循环遍历一个列表,然后再回到前面? - Python: Is there a way to loop through a list from a specific index that wraps back to the front onwards? 有没有办法在Python中循环遍历列表的子部分 - Is there a way to loop through a sub section of a list in Python 更有效的方式来遍历列表,然后在python中使用双循环 - More efficent way to loop through list then using a double loop in python Python中将列表从头到尾循环的最佳方法是什么? - What is the best way in Python to loop over a list back to front? 如何循环遍历在每个元素处停止的 python 列表 - How can I loop through a python list stopping at every element python:遍历字符串列表查找指定元素的索引 - python: loop through list of strings find index of specified element 循环遍历多个 txt 文件并计算 Python 中所选单词的频率 - Loop through multiple txt files and count frequencies of chosen word in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM