Python更改数组中的元素
问题描述:
如何更改数组中的元素?我有此代码,但我希望它会显示 [[5,5],[1,4]]
.但事实并非如此.仍然会打印 [[1,2 ,, [1,4]]
.
How I can change element in array?
I have this code, but I expected that it would print [[5,5],[1,4]]
. But it wouldn't. It still prints [[1,2],[1,4]]
.
x = [[1,2], [1,4]]
for element in x:
if element[1] == 2:
element = [5,5]
print x
答
更改列表元素需要索引.
Change a list element requires an index.
list_object[index] = new_value
使用 枚举
,您可以遍历列表并获取索引.
Using enumerate
, you can iterate the list and get a indexes.
>>> x = [[1,2], [1,4]]
>>> for i, element in enumerate(x):
... if element[1] == 2:
... x[i] = [5,5]
...
>>> x
[[5, 5], [1, 4]]