【问题标题】:Divide every element in a python nested array by an integer将python嵌套数组中的每个元素除以一个整数
【发布时间】:2018-10-12 17:05:19
【问题描述】:

我在 python 中有一个很大的嵌套列表,列表中的一些元素是 numpy 数组。其结构如下:

listExample[x][y][z] = an integer
listExample[x][y] = a numpy array

x、y 和 z 有多种组合。我想将列表数组中的所有整数(都在list[x][y][z]中)除以100。

列表/数组结构示例:

listExample[
 [
  [ [100, 200, 300], [230, 133, 234] ],
  [ [234, 232, 523], [231, 234, 554] ]
 ],
 [
  [ [701, 704, 204], [331, 833, 634] ],
  [ [734, 632, 523], [131, 434, 154] ]
 ] 
]

我正在尝试为上面的列表示例生成这样的输出:

listExample[
 [
  [ [1, 2, 3], [2.3, 1.33, 2.34] ],
  [ [2.34, 2.32, 5.23], [2.31, 2.34, 5.54] ]
 ],
 [
  [ [7.01, 7.04, 2.04], [3.31, 8.33, 6.34] ],
  [ [7.34, 6.32, 5.23], [1.31, 4.34, 1.54] ]
 ] 
]

我在上面的输入输出示例中使用了缩进,以便于读取多维数组。

关于 StackOverflow 的其他问题,使用 numpy 或类似的方法将列表除以整数:

listExample = [i/100 for i in listExample]

但是,这不起作用,因为这是一个嵌套数组。它会吐出这个错误:

TypeError: unsupported operand type(s) for /: 'list' and 'int'

那么,我应该如何将数组/列表中的每个整数除以 100?

【问题讨论】:

  • 现在是使用 numpy 还是 listminimal reproducible example
  • @Jean-FrançoisFabre 这是一个列表,其中包含 numpy 数组作为元素。 list[x][y] 中的每个元素都是一个带有 z 个元素的 numpy 数组。
  • 输入数据和预期输出的样本会很有帮助
  • @Jean-FrançoisFabre 是的,完成了。
  • 您的示例是列表列表,而不是 np.array 列表列表

标签: python arrays python-3.x list multidimensional-array


【解决方案1】:

你可以使用 NumPy 的 divide 方法:

import numpy as np 
arr1 = [
 [
  [ [100, 200, 300], [230, 133, 234] ],
  [ [234, 232, 523], [231, 234, 554] ]
 ],
 [
  [ [701, 704, 204], [331, 833, 634] ],
  [ [734, 632, 523], [131, 434, 154] ]
 ] 
]
out = np.divide(arr1, 100) 

print(out)

输出:

[[[[1.   2.   3.  ]
   [2.3  1.33 2.34]]

  [[2.34 2.32 5.23]
   [2.31 2.34 5.54]]]


 [[[7.01 7.04 2.04]
   [3.31 8.33 6.34]]

  [[7.34 6.32 5.23]
   [1.31 4.34 1.54]]]]

【讨论】:

    【解决方案2】:

    如果您愿意使用第 3 方库,则可以使用 numpy 进行矢量化解决方案:

    设置

    import numpy as np
    
    lst = [
     [
      [ [100, 200, 300], [230, 133, 234] ],
      [ [234, 232, 523], [231, 234, 554] ]
     ],
     [
      [ [701, 704, 204], [331, 833, 634] ],
      [ [734, 632, 523], [131, 434, 154] ]
     ] 
    ]
    

    解决方案

    res = np.array(lst)/100
    
    array([[[[ 1.  ,  2.  ,  3.  ],
             [ 2.3 ,  1.33,  2.34]],
    
            [[ 2.34,  2.32,  5.23],
             [ 2.31,  2.34,  5.54]]],
    
    
           [[[ 7.01,  7.04,  2.04],
             [ 3.31,  8.33,  6.34]],
    
            [[ 7.34,  6.32,  5.23],
             [ 1.31,  4.34,  1.54]]]])
    

    【讨论】:

    • 我收到一个错误:TypeError: unsupported operand type(s) for /: 'list' and 'int'
    • @AdityaRadhakrishnan,请参阅更新。我无法复制您的错误。
    【解决方案3】:

    遍历列表,然后除以 numpy 数组。

    loloa = [[np.array([1,2]), np.array([3,4])],[np.array([5,6])]]
    for loa in loloa:
        for i in range(len(loa)):
            loa[i] = loa[i]/100
    print(loloa)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-15
      • 1970-01-01
      • 2014-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多