简体   繁体   English

Python 替换元素 = 二维数组中的键

[英]Python replace elements = key in 2D array

Assuming a 2d list exists that has the values [[0, 0], [1, 0]]假设存在一个二维列表,其值为[[0, 0], [1, 0]]

Is there a way to loop through it such to replace every 0 with a 2 (for example)?有没有办法循环遍历它,例如用 2 替换每个 0(例如)?

My first approach was as follows but although the value of l was updated, the entry in the list was not.我的第一种方法如下,但尽管 l 的值已更新,但列表中的条目却没有。 Any ideas?有任何想法吗?

for k in g:
     for l in k:
          if not l == 1:
               l = 2

You can use list-comprehension:您可以使用列表理解:

lst = [[0, 0], [1, 0]]

lst = [[2 if val == 0 else val for val in subl] for subl in lst]
print(lst)

Prints:印刷:

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

Assigning values to the loop variables updates their value but does not modify the the original list.为循环变量赋值会更新它们的值,但不会修改原始列表。 To modify the list, you need to reference its elements directly.要修改列表,您需要直接引用其元素。 The code below does this and replaces all 0s in the list with 2s.下面的代码执行此操作并将列表中的所有 0 替换为 2。

l = [[0, 0], [1, 0]]
for i in range(len(l)): 
    for j in range(len(l[i])): 
        if l[i][j] == 0: 
            l[i][j] = 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM