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

时间:2018-03-09 20:31:22

标签: python list multidimensional-array replace find

与此问题类似:finding and replacing elements in a list (python) 但是有一个多维数组。例如,我想用0代替所有N:

list =
[['N', 0.21],
 [-1, 6.6],
 ['N', 34.68]]

我想将其更改为:

list =
[[0, 0.21],
 [-1, 6.6],
 [0, 34.68]]

4 个答案:

答案 0 :(得分:4)

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

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]

输出:

[[0, 0.21], [-1, 6.6], [0, 34.68]]

答案 1 :(得分:0)

试试这个:

for l in list:
    while 'N' in l:
        l[l.index('N')]=0

答案 2 :(得分:0)

不要将list用作变量名:

list1 =[['N', 0.21],
        [-1, 6.6],
        ['N', 34.68]]

[j.__setitem__(ii,0) for i,j in enumerate(list1) for ii,jj in enumerate(j) if jj=='N']


print(list1)

输出:

[[0, 0.21], [-1, 6.6], [0, 34.68]]

答案 3 :(得分:0)

我想我已经找到一种方法来处理任何尺寸的数组,即使该数组的元素不都具有相同的尺寸,例如:

array=[
  [
   ['N',2],
   [3,'N']
  ],
  [
   [5,'N'],
   7
  ],
]

首先,定义一个函数来检查变量是否可迭代,例如In Python, how do I determine if an object is iterable?中的变量:

def iterable(obj):
    try:
        iter(obj)
    except Exception:
        return False
    else:
        return True

然后,使用以下递归函数将“ N”替换为0:

def remove_N(array):
    "Identify if we are on the base case - scalar number or string"
    scalar=not iterable(array) or type(array)==str #Note that strings are iterable.
    "BASE CASE - replace "N" with 0 or keep the original value"
    if scalar:
        if array=='N':
            y=0
        else:
            y=array
        "RECURSIVE CASE - if we still have an array, run this function for each element of the array"
    else:
        y=[remove_N(i) for i in array]
    "Return"
    return y

示例输入的输出:

print(array)
print(remove_N(array))

收益:

[[['N', 2], [3, 'N']], [[5, 'N'], 7]]
[[[0, 2], [3, 0]], [[5, 0], 7]]

你怎么看?