【问题标题】:finding and replacing elements in a multidimensional list (python)在多维列表中查找和替换元素(python)
【发布时间】:2018-08-18 11:50:42
【问题描述】:

与这个问题类似: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]]

【问题讨论】:

  • 尝试过列表理解?

标签: python list multidimensional-array replace find


【解决方案1】:

我想我已经找到了一种方法来处理任何维度的数组,即使数组的元素并非都具有相同的维度,例如:

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

你怎么看?

【讨论】:

    【解决方案2】:

    不要使用列表作为变量名:

    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】:

      试试这个:

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

      【讨论】:

      • 子列表中有多个“N”时会发生什么?
      【解决方案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]]
      
      猜你喜欢
      • 2019-02-20
      • 2011-02-04
      • 2018-08-05
      • 1970-01-01
      • 2015-09-06
      • 2015-04-26
      • 2018-01-11
      • 2019-07-04
      • 1970-01-01
      相关资源
      最近更新 更多