简体   繁体   中英

In Python, how do I skip an item in a list when using nested for loops, but only in certain conditions?

It's a pretty niche situation I've come across, but I need to reuse one list in multiple nested for loops and also avoid repeats. Here's a simplified example of what I'm trying to do:

my_list = [7,1,4,2,6,5,3]
for x in my_list:
  for y in my_list:
    if y == x:
      #advance to the next item in my_list
    for z in my_list:
      while z == x or z == y:
        #advance to the next item in my_list
      #do stuff

I am also wondering if there is a cleaner way to avoid repeats than using the while loop, because the loop is going to be nested up to 9 times, so it would make for messy while loops. I tried converting my_list to an iterator using iter(my_list) and then using y = next(my_list), which normally would work, but then the next for loop with z will not start at the beginning of my_list. The only solution I can think of is to use while loops instead of for loops so I can do something like the following:

z = 0
while z < 7:
  while z == y or z == x:
    z += 1
  #do stuff with my_list[z]
  z += 1

I'd really like to avoid this approach if possible. Is there any way I can do it using for loops?

EDIT: Commented out the lines that aren't code

You can use pass to not do anything, for example:

L = [1, 2, 0, 4]
for element in L:
    if element == 0:
        pass
    else:
        print(element)

This will print: 1, 2 and 4 since it will skip 0

If you want to stop the current loop, use break :

for element in L:
    if element == 0:
        break
    else:
        print(element)

This will print out 1, 2 and then the loop stops.

So, which one you use depends on how you want to advance to the next item. break will stop the current for loop and take you back to the previous for loop, while pass will continue the loop but just not do anything with that element

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