Python更改数组中的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34289516/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:45:03  来源:igfitidea点击:

Python change element in array

pythonlist

提问by Kenenbek Arzymatov

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]].

如何更改数组中的元素?我有这个代码,但我希望它会打印[[5,5],[1,4]]. 但它不会。它仍然打印[[1,2],[1,4]].

x = [[1,2], [1,4]]
for element in x:
    if element[1] == 2:
        element = [5,5]
print x

采纳答案by falsetru

Change a list element requires an index.

更改列表元素需要索引。

list_object[index] = new_value

Using enumerate, you can iterate the list and get a indexes.

使用enumerate,您可以迭代列表并获取索引。

>>> x = [[1,2], [1,4]]
>>> for i, element in enumerate(x):
...     if element[1] == 2:
...         x[i] = [5,5]
...
>>> x
[[5, 5], [1, 4]]