Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

python - Adding value to one of the elements in array

I have a list of n elements, and I'm trying to make a new nxn array in which all the rows are the elements of my previous list (for example, if I have a list u=[a,b], then the array is y=[u,u]=[[a,b],[a,b]]) and for all the values of index i=1,2,... I want all the elements y[i][i] to be added with additional values h (that is, if the list is p=[a,b], then the final product is q=[p,p]=[[a+h,b],[a,b+h]]).

If I made the program to be straightforward like this

u=[[1,2],[1,2]]
h=1e-3
for i in range(2):
  u[i][i]+=1
print(u)

it would print out what I want correctly

[[2, 2], [1, 3]]

but if I did it in a loop like this

x=[1,2]
u=[]
h=1e-3
for i in range(len(x)):
  u.append(x)
for i in range(2):
  u[i][i]+=1
print(u)

the program would assume that I'm trying to add 1 to each of its elements like this

[[2, 3], [2, 3]]

I did check "u" before adding 1 to its u[i][i] elements with the second code and it prints out u=[[1,2],[1,2]] as well. So what did I do wrong here?

question from:https://stackoverflow.com/questions/65546178/adding-value-to-one-of-the-elements-in-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
x=[1,2]
u=[]
h=1e-3

for i in range(len(x)):
  u.append(x.copy())

for i in range(2):
  u[i][i] +=1

print(u)

You got almost there! In fact, when you append x to u twice, you make "linked twins". Which means: x stays in in u. And you have x twice. If you modify u[0] which is x, then you modify u[1] which is also x.

To avoid that, use x.copy().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...