查找和替换多维列表中的元素(python)

Sla*_*ion 0 python replace list find multidimensional-array

类似于这个问题:查找和替换列表(python)中的元素, 但使用多维数组。例如,我想用 0 替换所有 N:

list =
[['N', 0.21],
 [-1, 6.6],
 ['N', 34.68]]
Run Code Online (Sandbox Code Playgroud)

我想把它改成:

list =
[[0, 0.21],
 [-1, 6.6],
 [0, 34.68]]
Run Code Online (Sandbox Code Playgroud)

Aja*_*234 6

您可以使用嵌套列表理解:

l = [['N', 0.21], [-1, 6.6], ['N', 34.68]]
new_l = [[0 if b == 'N' else b for b in i] for i in l]
Run Code Online (Sandbox Code Playgroud)

输出:

[[0, 0.21], [-1, 6.6], [0, 34.68]]
Run Code Online (Sandbox Code Playgroud)

  • [“切勿使用字符 'l'(小写字母 el)、'O'(大写字母 oh)或 'I'(大写字母眼睛)作为单个字符变量名称。”](http://pep8.org/ #要避免的名字) (3认同)