gpt4 book ai didi

python - 从列表或元组创建新的 numpy 数组

转载 作者:行者123 更新时间:2023-12-01 00:56:16 24 4
gpt4 key购买 nike

创建新的 numpy 数组时,可以像这样制作它们:

a = numpy.array((2, 5))
b = numpy.array((a[0] + 1, 10))

或者像这样:

a = numpy.array([2, 5])
b = numpy.array([a[0] + 1, 10])

哪种方式更好?

最佳答案

经过一些基于 @leopardshark 的测试的answer ,似乎只有基于常量初始化数组,元组才会更好。如果您从变量元组/列表进行初始化,则差异可以忽略不计

常量测试设置

import dis, timeit

list_timing = timeit.timeit('numpy.array([2, 5])', setup = 'import numpy', number = 1000000)
tuple_timing = timeit.timeit('numpy.array((2, 5))', setup = 'import numpy', number = 1000000)

print(f"List mean time: {list_timing}")
>>> 0.6392972
print(f"Tuple mean time: {tuple_timing}")
>>> 0.6296533

这里的反汇编输出与 @leopardshark 相同的

变量测试设置

import dis, timeit
x, y = 2, 5

list_timing = timeit.timeit('numpy.array([x, y])', setup = 'import numpy; x, y = 2, 5', number = 1000000)
tuple_timing = timeit.timeit('numpy.array((x, y))', setup = 'import numpy; x, y = 2, 5', number = 1000000)

print(f"List mean time: {list_timing}")
>>> 0.6279472
print(f"Tuple mean time: {tuple_timing}")
>>> 0.6288363

print(dis.dis('numpy.array([x, y])'))
>>> 1 0 LOAD_NAME 0 (numpy)
>>> 2 LOAD_METHOD 1 (array)
>>> 4 LOAD_NAME 2 (x)
>>> 6 LOAD_NAME 3 (y)
>>> 8 BUILD_LIST 2
>>> 10 CALL_METHOD 1
>>> 12 RETURN_VALUE

print(dis.dis('numpy.array((x, y))'))
>>> 1 0 LOAD_NAME 0 (numpy)
>>> 2 LOAD_METHOD 1 (array)
>>> 4 LOAD_NAME 2 (x)
>>> 6 LOAD_NAME 3 (y)
>>> 8 BUILD_TUPLE 2
>>> 10 CALL_METHOD 1
>>> 12 RETURN_VALUE

反汇编的输出是相同的,而时序更接近

关于python - 从列表或元组创建新的 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56227154/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com