没有枚举的更好的迭代模式

2024-09-27 00:16:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我经常使用以下代码模式:

def update_missing_content_type(cls):
    items_missing_content_type = ItemMaster.objects.filter(content_type__isnull=True)
    num_items = items_missing_content_type.count()
    for num, item in enumerate(items_missing_content_type):
        if num % 100 == 0:
            log.info('>>> %s / %s updated...' % (num+1, num_items))
        # do something

enumerate可以是非理想的,尽管如果查询的大小是非平凡的。但是,我仍然需要知道脚本的进度(它可能会运行10个小时等等)。你知道吗

有什么比上面更好的模式可以在记录一般过程的同时对一些结果进行处理呢?你知道吗


Tags: 代码objectsdeftype模式updateitemscontent
2条回答

Enumerate的行为类似于迭代器,将动态生成整数。更多详细信息:What is the implementation detail for enumerate? Enumerate应该在性能上表现得几乎相同,就像只是遍历iterable的索引并查找项一样。你知道吗

大概您需要有日志的索引和#do something中的项,这样我们就可以对两者计时。以下是我的结果:

python -m timeit -s 'test=range(10)*1000' 'for i, elem in enumerate(test): pass' 1000 loops, best of 3: 370 usec per loop

python -m timeit -s 'test=range(10)*1000' 'for i in xrange(len(test)): elem=test[i]' 1000 loops, best of 3: 397 usec per loop

在这个用例中,这两种方法在速度上似乎没有什么不同。但是,如果您不需要索引,则会有区别: python -m timeit -s 'test=range(10)*1000' 'for elem in test: pass' 10000 loops, best of 3: 153 usec per loop

The enumerate can be non-ideal though if the size of the Query is non-trivial.

enumerate生成一个迭代器,而不是一个列表,因此它不会通过预先分配一堆内存来消耗额外的内存。另外,它不能在无限长的生成器上工作。你知道吗

相关问题 更多 >

    热门问题