简体   繁体   English

如何在循环结束时触发某些东西?

[英]How to trigger something on the close of a loop?

Is this possible? 这可能吗? I want to print lines in my file 5 at a time (to send to an API in a batch). 我想一次在我的文件中打印行(以批量发送到API)。 But when I get to the last few lines they never print because there are less than 5, never triggering my if statement to print. 但是当我到达最后几行时,他们从不打印,因为少于5行,从不触发我的if语句打印。 SO I figured one way to tackle this is to print the remaining lines when the loop closes. 所以我认为解决这个问题的一种方法是在循环关闭时打印剩余的行。

The current code is messy and redundant but this is the idea: 当前的代码是混乱和多余的,但这是个想法:

urls = []
urls_csv = ""
counter = 0

with open(urls_file) as f:
    for line in f:

        # Keep track of the lines we've went through
        counter = counter + 1

        # If we have 5 urls in our list it's time to send them to the API call
        if counter > 5:
            counter = 0
            urls_csv = ",".join(urls) # turn the python list into a string csv list
            do_api(urls_csv) # put them to work

            urls = [] # reset the value so we don't send the same urls next time
            urls_csv = "" # reset the value so we don't send the same urls next time
         # Else append to the url list
         else:
            urls.append(line.strip))

Also - Generally speaking, is there a better way to tackle this? 另外 - 一般来说,有没有更好的方法来解决这个问题?

You can group them into sets of 5 lines at a time with the itertools grouper recipe . 您可以使用itertools石斑鱼配方将它们一次分组成5行。

import itertools

def grouper(iterable, n, fillvalue=None):
    args = [iter(iterable)] * n
    return itertools.zip_longest(*args, fillvalue=fillvalue)

with open(...) as f:
    for group in grouper(f, 5, fillvalue=""):
        do_api(",".join([g.strip() for g in group if g]))

What do you think of 你怎么看

urls = []

with open(urls_file) as f:
    while True:
        try:
            for i in range(5):
                urls.append(next(f).rstrip())
            print(urls)  # i.e. you have the list of urls, now use it/put it to work
            urls = []
        except StopIteration:
            print(urls)
            break

with an input file of 输入文件

line1
line2
line3
line4
line5
line6
line7

it produces 它产生

['line1', 'line2', 'line3', 'line4', 'line5']
['line6', 'line7']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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