简体   繁体   中英

Proper style to implement control flow in python loop

I am not sure if the title of this question is correct or even the right question to ask (sorry if this is a duplicate).

What is the best (most pythonic) way to manage control flow in a loop in python, I specifically want to skip over items in a filter list. Here are my two approaches:

Idea 1:

items=["a","b","c","x","b"]
filterList=["x","y","z"]
for i in items:
    if i in filterList:
        continue

    ... Code for working with i

Idea 2:

items=["a","b","c","x","b"]
filterList=["x","y","z"]
for i in items:
    if i not in filterList:
        ... Code for working with i

Is one of these two styles more pythonic or readable than the other?

Edit 1: One thing to note is that items will potentially have duplicates, updated code to reflect this.

You could use list comprehension:

items = ...
filterList = ...

filtered_items = (i for i in items if i not in filterList)

for i in filtered_items:
   do the thing

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