简体   繁体   English

为什么 enumerate() 在这里没有按预期工作?

[英]Why does enumerate() not work as intended here?

I've trying to use enumerate to do something every nth iteration.我试图使用 enumerate 在每 n 次迭代中做一些事情。 In the below example I'm using a chunked iterable.在下面的示例中,我使用了一个分块的可迭代对象。 The original iterable is a list of 1000000 URLs and the generator, it's broken into 1000 chunks.原始的可迭代对象是一个包含 1000000 个 URL 和生成器的列表,它被分成 1000 个块。 Now if I use:现在,如果我使用:

if count % 2 == 0:

it works as intended ie every second chunk, it prints out abc .它按预期工作,即每隔一个块,它打印出abc However if I try to use:但是,如果我尝试使用:

if count % 1 == 0:

instead of abc being printed out after every chunk completes, it prints abc after every individual item in the original list completes.它不是在每个块完成后打印出abc ,而是在原始列表中的每个单独项目完成后打印abc In other words, I get a million abc outputs instead of 1000. What am I doing wrong?换句话说,我得到了一百万个abc输出而不是 1000 个。我做错了什么?

def chunk_iterable(iterable, chunk_size):
    chunk = []
    for item in iterable:
        chunk.append(item)
        if len(chunk) == chunk_size:
            yield chunk
            chunk = []
    if chunk:
        yield chunk


async def make_async_requests(directory, file, urls):
    sem = asyncio.BoundedSemaphore(50)
    chunk_size = 10000
    async with aiohttp.ClientSession() as session:
        for count, chunk in tqdm.tqdm(enumerate(chunk_iterable(urls, chunk_size)), total=len(urls)/chunk_size)):
            await tqdm.asyncio.tqdm.gather(*[write_to_file(url, sem, session) for url in chunk])
            if count % 1 == 0:
                print("abc")
                continue

The problem here isn't enumerate() , it's the use of the modulo operator here:这里的问题不是enumerate() ,而是这里模运算符的使用:

if count % 1 == 0:

This condition will always be true because the modulo of 1 will always be a zero, if you want a thousand outputs instead of a million (if it's an exact million) try:这种情况将始终为真,因为 1 的模将始终为零,如果您想要一千个输出而不是一百万(如果它是一百万)尝试:

if count % 1000 == 0:

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

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