Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

python - Skip items in a list range and continue with the rest

I want to print out some items in a list, but I want to skip a couple of items and continue with the rest.

This is an example of my code and how I do it so far.

mylist = ["dog","cat","lion","wolf","zebra","monkey","bear","eagle", "bison"]
for item in mylist:
    if item == mylist[4]:
        continue
    if item == mylist[5]:
        continue
    if item == mylist[6]:
        continue
    print(item)

How can I do the same thing but without using multiple if statements?

question from:https://stackoverflow.com/questions/65642579/skip-items-in-a-list-range-and-continue-with-the-rest

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use an indexed for-loop (using the index to retrieve the element).

mylist = ["dog", "cat", "lion", "wolf", "zebra", "monkey", "bear", "eagle", "bison"]

for i in range(len(mylist)):
    if i in [4, 5, 6]:             # element indices to skip
        continue
    print(mylist[i])               # procedures desired

The alternative way to do so, is to modify the for-loop range, which would save two lines of code doing if. (This is a relatively bad idea)

mylist = ["dog", "cat", "lion", "wolf", "zebra", "monkey", "bear", "eagle", "bison"]

for i in (mylist[:4]+mylist[7:]):  # exclude the skipped ones
    print(mylist[i])               # procedures desired

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...