[英]Python replacing all list elements instead of the indexed list element in for loop
I want to replace the kth element of the kth element of the list.我想替换列表的第 k 个元素的第 k 个元素。
Eg,例如,
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
to到
[[1, 0, 0],
[0, 1, 0],
[0, 0, 1]]
BUT python does not seem to want to do that and instead is replacing each value for each element.但是 python 似乎不想这样做,而是替换每个元素的每个值。
I run this:我运行这个:
# Triangle Vertices
V = [[0, 1], [-1, 0], [1, 0]]
# Triangles (indices of V in clockwise direction)
T = [[1, 0, 2]]
# Creating sub-triangles
bary_point = [0, 0.5]
v_list = []
for t in T:
print(t)
for k in range(3):
v_list.append(V)
v_list[k][k] = bary_point # <-- This line
print('v_list: ')
print(v_list)
and it produces this:它产生了这个:
v_list:
[[[0, 0.5], [0, 0.5], [0, 0.5]],
[[0, 0.5], [0, 0.5], [0, 0.5]],
[[0, 0.5], [0, 0.5], [0, 0.5]]]
but I want this:但我想要这个:
v_list:
[[[0, 0.5], [-1, 0], [1, 0]],
[[0, 1], [0, 0.5], [1, 0]],
[[0, 1], [-1, 0], [0, 0.5]]]
Am I doing something wrong?难道我做错了什么? I am on Python 3.10.0我在 Python 3.10.0
Thank you.谢谢你。
EDIT Solution: Change编辑解决方案:更改
v_list.append(V)
to到
v_list.append(V.copy())
Thank you!谢谢!
You are appending the same reference to the list V
, and when you change v_list[k][k]
you are changing V
, one solution would be to append a copy of the list, by using V.copy()
as argument to append
.您将相同的引用附加到列表V
,并且当您更改v_list[k][k]
时,您正在更改V
,一个解决方案是 append 列表的副本,使用V.copy()
作为append
的参数.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.