【问题标题】:Convert a 3D numpy array with strings to a python list in a certain way以某种方式将带有字符串的 3D numpy 数组转换为 python 列表
【发布时间】:2022-01-17 19:37:53
【问题描述】:

考虑以下代码:

array = np.array2string(np.arange(27).reshape(3,3,3))

这将创建一个 3D 维度的 numpy 数组。输出将如下所示:

[[[ 0  1  2]
  [ 3  4  5]
  [ 6  7  8]]

 [[ 9 10 11]
  [12 13 14]
  [15 16 17]]

 [[18 19 20]
  [21 22 23]
  [24 25 26]]]

我想将此 numpy 数组转换为 python 列表,其中每个索引对应于 numpy 数组中的一行。重要的是要注意每个数字之间有一个空格。所以输出看起来像这样:

    Index Type Size  Value 
    0     str    5   0 1 2 
    1     str    5   3 4 5
    2     str    5   6 7 8 
    3     str    5   9 10 11
....
.... and so on

我将如何编码?

【问题讨论】:

  • 5 号应该是什么意思?
  • 是字符串的大小。例如,如果您有一个字符串“1 2”,其大小为 3,而“Hello”的大小为 5。

标签: python arrays string numpy


【解决方案1】:

您可以通过一系列替换来做到这一点:

my_array = np.array2string(np.arange(27).reshape(3,3,3))
# remove brackets
my_array = my_array.replace('[', '').replace(']', '').split('\n')
# remove space at the beginning of each line
my_array = [line.lstrip() for line in my_array]
# keep only strings that are not empty
my_array = [line for line in my_array if line]

结果:

['0  1  2',
 '3  4  5',
 '6  7  8',
 '9 10 11',
 '12 13 14',
 '15 16 17',
 '18 19 20',
 '21 22 23',
 '24 25 26']

【讨论】:

    猜你喜欢
    • 2017-03-10
    • 2019-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-07
    • 2018-09-19
    • 1970-01-01
    • 2023-01-02
    相关资源
    最近更新 更多