简体   繁体   中英

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?

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:

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.

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. Hopefully I understood your question correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM