Python更改数组中的元素 [英] Python change element in array
本文介绍了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]]
这篇关于Python更改数组中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文