简体   繁体   中英

How to have enumerate function cycles through the data multiple times

I want this set of code to run every time a line contains CAFE. Currently, it only runs for the first time CAFE appears. I think I need to change the index inside of the enumerate function from dataset to something that specifies that the code will begin counting value for i again after each line that contains CAFE.

with open('data.txt', 'r') as dataset:
    for line in dataset:
        if 'CAFE' in line:
             for i, line in enumerate(dataset):
                 if i > 1 and i < 130 and i %2 == 0:
                     print(line)

                 else:
                    pass
        else:
            pass 

It is because when you enter the first loop, you'll be traversed to 1st line in text file.

In the first iteration, when the second loop iterates through all lines, the dataset object points to EOF(end of file). So after 1st iteration, you'll be reached EOF. That's the reason it only runs for the first time.

Instead, you can store all lines in a list and then perform your process on the list.

Code:

data = []
with open('data.txt', 'r') as dataset:
    for line in dataset:
        data.append(line)

for line in data:
    if 'CAFE' in line:
         for i, lt in enumerate(data):
             if i > 1 and i < 130 and i %2 == 0:
                 print(lt)
             else:
                pass
    else:
        pass 

And one more thing to notice is you've named the variable as "line" in both the for loops which is a bad practice.

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