[英]Simple question about slicing and for loops without indices
If I was making this loop:如果我正在制作这个循环:
for i in range(len(array)):
for j in range(len(array)+1):
# some code using array[i] and array[j]
Would there be a way to do the same thing in this format?有没有办法以这种格式做同样的事情?
for element in array:
for next_element in array:
# some code using element and next_element
Or would I just be better off using the i, j
format?还是我最好使用
i, j
格式?
You mean like this?你的意思是这样吗?
for element in array:
for next_element in array[1:]:
# some code using elemnt
I guess it all depends on your end goal or personal preference.我想这一切都取决于你的最终目标或个人喜好。 What I did here is start our second loop from the second value towards the end.
我在这里所做的是从第二个值开始我们的第二个循环。 If you need the indexes, you can use
enumerate()
like this:如果需要索引,可以像这样使用
enumerate()
:
for index_a, element in enumerate(array):
for index_b, next_element in enumerate(array[1:]):
# some code using the elements and the indexes
for element in array:
for next_element in array[1:]:
# some code using element and next_element
Please note that your first loop will throw an index error because j goes out of bounds on the last iteration.请注意,您的第一个循环将引发索引错误,因为 j 在最后一次迭代中超出范围。
The i and the j could be anything you want it to be, inside the for loop it's going to mean the same thing. i 和 j 可以是你想要的任何东西,在 for 循环中它的意思是一样的。 Hopefully I understood your question correctly.
希望我正确理解了您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.