Better iteration pattern without enumerating

David542

I have the following pattern in code which I use quite frequently:

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

The enumerate can be non-ideal though if the size of the Query is non-trivial. However, I still need to know the progress of the script (it might run for ten hours, etc.).

What would be a better pattern than the above to do something over a number of results while logging the general process of it?

drglove

Enumerate behaves as an iterator, and will produce the integer numberings on the fly. More details here: What is the implementation detail for enumerate? Enumerate should behave almost identically in performance as to just going over the indices of the iterable and looking up the item.

Presumably you need to have the index for logging and the item in #do something, so we can time the two. Here are my results:

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

There seems to be no difference in speed between the two as expected in this use case. There is however a difference if you don't need the index: python -m timeit -s 'test=range(10)*1000' 'for elem in test: pass' 10000 loops, best of 3: 153 usec per loop

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

Efficient way to add variables and constraints through Gurobi Python without enumerating through all elements

Better pattern for partial specialization disambiguation precedence chain?

Array/List iteration without extra object allocations

Is there a better way to achieve this CSS animation without Javascript?

Better SQL Query to split alphanumeric string based on pattern

NSArray enumerating by group

Unique values from 1D-array, without iteration

How to select result from dataframe according to specific pairs without iteration?

Implement Strategy Pattern in C++ without Pointers

Enumerating python matrix by cell value

Is there a better way to model this access pattern than to use two global secondary indexes (GSI)?

How do I specify a zone offset in a DateTimeFormatterBuilder without using a pattern?

Call stored procedure in EF 6 Repository Pattern without output parameters

PowerShell: Split String without removing the split-pattern?

How to use the chained builder pattern in a loop without creating a compiler error?

Override static pattern rule in Makefile (without it giving a warning)

Net core MVC clean architecture without repository pattern

extending spring mvc controller without using adapter pattern

Is it possible to implement the "virtual constructor" pattern in C# without casts?

is IEnumerable enumerated on call of the method or when enumerating the response

AVR clean pin aliasing solution - enumerating I/O bits

How to grep for cases where a pattern doesn't exist without perl-like lookahead?

Pagination iteration counter

Parallel python iteration

Introspection and iteration on an Enum

Implementing RAII on a folder iteration

Parameter pack iteration

Iteration of objects on a Form

Clojure iteration and nesting data

TOP 一覧

  1. 1

    STSでループプロセス「クラスパス通知の送信」のループを停止する方法

  2. 2

    Spring Boot Filter is not getting invoked if remove @component in fitler class

  3. 3

    Python / SciPyのピーク検出アルゴリズム

  4. 4

    セレンのモデルダイアログからテキストを抽出するにはどうすればよいですか?

  5. 5

    tkinterウィンドウを閉じてもPythonプログラムが終了しない

  6. 6

    androidsoongビルドシステムによるネイティブコードカバレッジ

  7. 7

    ZScalerと証明書の問題により、Dockerを使用できません

  8. 8

    VisualStudioコードの特異点/ドッカー画像でPythonインタープリターを使用するにはどうすればよいですか?

  9. 9

    ビュー用にサイズ変更した後の画像の高さと幅を取得する方法

  10. 10

    二次導関数を数値計算するときの大きな誤差

  11. 11

    Ansibleで複数行のシェルスクリプトを実行する方法

  12. 12

    画像変更コードを実行してもボタンの画像が変更されない

  13. 13

    Reactでclsxを使用する方法

  14. 14

    Three.js indexed BufferGeometry vs. InstancedBufferGeometry

  15. 15

    __init__。pyファイルの整理中に循環インポートエラーが発生しました

  16. 16

    PyTesseractを使用した背景色のため、スクリーンショットからテキストを読み取ることができません

  17. 17

    値間の一致を見つける最も簡単な方法は何ですか

  18. 18

    reCAPTCHA-エラーコード:ユーザーの応答を検証するときの「missing-input-response」、「missing-input-secret」(POSTの詳細がない)

  19. 19

    三項演算子良い練習の代わりとしてOptional.ofNullableを使用していますか?

  20. 20

    好き/愛の関係のためのデータベース設計

  21. 21

    エンティティIDを含む@RequestBody属性をSpringの対応するエンティティに変換します

ホットタグ

アーカイブ