在python中生成元组的最快方法是什么:(1.0,0.0,0.0,2.0,0.0,0.0,...,N,0.0,0.0)?

gma*_*gno 0 python tuples

寻找用标题中提到的模式生成元组的最快方法,即:

(1.0, 0.0, 0.0, 2.0, 0.0, 0.0, ..., N, 0.0, 0.0)
Run Code Online (Sandbox Code Playgroud)

对于任意的正n表示方面:round(N) == N

Tim*_*ers 5

谁知道?;-)在CPython中,“诀窍”通常涉及避免显式的Python级别的循环,以及避免二次时间的链接。这是一种方法:

def gentup(N):
    NI = round(N)
    assert N == NI
    result = [0.] * (3 * NI)
    result[::3] = map(float, range(1, NI + 1))
    return tuple(result)
Run Code Online (Sandbox Code Playgroud)

然后,例如

>>> gentup(4)
(1.0, 0.0, 0.0, 2.0, 0.0, 0.0, 3.0, 0.0, 0.0, 4.0, 0.0, 0.0)
Run Code Online (Sandbox Code Playgroud)

然后,所有实际工作都以“ C速度”运行,甚至float只被查询一次(尽管被调用了 round(N)几次)。