根据我对python的切片表示法的理解,使用切片表示法浅层复制有问题的数组。
但是,如果将数组切片设置为某个值,会发生什么?
例如:
import numpy as np
a=np.zeros(shape=(3,2))
b=np.zeros(shape=(3,2))
for i in range(0,2):
a[:,i]=i+1
for i in range(0,2):
for x in range(0,3):
b[x,i]=i+1
print a
print b
这里a和b是相同的。
我不应该以这种方式使用切片表示法吗? (我从未见过有人以这种方式使用切片表示法,所以我觉得可能会有)
答案 0 :(得分:0)
我认为没有理由不能使用您的代码。下面是对上面扩展的样本的速度测试,以确保它需要足够的时间进行注册。
import numpy as np import time a=np.zeros(shape=(4,3)) b=np.zeros(shape=(4,3)) print "--before--" print a print "" print b start_time = time.time() for i in range(0,3): a[:,i]=i+1 time1 = time.time() for i in range(0,3): for x in range(0,4): b[x,i]=i+1 time2 = time.time() print "--after--" print a print ("this took %s seconds\n"% (time1-start_time)) print b print ("this took %s seconds\n"% (time2-time1)) print "--done--\n"
--before-- [[ 0. 0. 0.] [ 0. 0. 0.] [ 0. 0. 0.] [ 0. 0. 0.]] [[ 0. 0. 0.] [ 0. 0. 0.] [ 0. 0. 0.] [ 0. 0. 0.]] --after-- [[ 1. 2. 3.] [ 1. 2. 3.] [ 1. 2. 3.] [ 1. 2. 3.]] this took 1.21593475342e-05 seconds [[ 1. 2. 3.] [ 1. 2. 3.] [ 1. 2. 3.] [ 1. 2. 3.]] this took 7.86781311035e-06 seconds --done--