What is the fastest way to initialize an integer array in python?

前端 未结 6 391
终归单人心
终归单人心 2020-12-11 06:57

Say I wanted to create an array (NOT list) of 1,000,000 twos in python, like this:

array = [2, 2, 2, ...... , 2]

What would be a fast but simple

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-11 07:11

    The currently-accepted answer is NOT the fastest way using array.array; at least it's not the slowest -- compare these:

    [source: johncatfish (quoting chauncey), Bartek]
    python -m timeit -s"import array" "arr = array.array('i', (2 for i in range(0,1000000)))"
    10 loops, best of 3: 543 msec per loop
    
    [source: g.d.d.c]
    python -m timeit -s"import array" "arr = array.array('i', [2] * 1000000)"
    10 loops, best of 3: 141 msec per loop
    
    python -m timeit -s"import array" "arr = array.array('i', [2]) * 1000000"
    100 loops, best of 3: 15.7 msec per loop
    

    That's a ratio of about 9 to 1 ...

提交回复
热议问题