python - Numpy/展平列表

标签 python numpy numpy-ndarray

我创造了这个角色

list1 = [['20']*3,['35']*2,['40']*4,['10']*2,['15']*3]

结果:

[['20', '20', '20'], ['35', '35'], ['40', '40', '40', '40'], ['10', '10'], ['15', '15', '15']]

我可以使用列表理解将其转换为单个列表

charlist = [x for sublist in list1 for x in sublist]
print(charlist)
['20', '20', '20', '35', '35', '40', '40', '40', '40', '10', '10', '15', '15', '15']

我想知道如何使用 numpy 做到这一点

listNP=np.array(list1)

给出输出:

array([list(['20', '20', '20']), list(['35', '35']),
       list(['40', '40', '40', '40']), list(['10', '10']),
       list(['15', '15', '15'])], dtype=object)

事实上,listNP.flatten() 给出了相同的输出结果。可能我在将列表转换为 numpy 数组时错过了一个步骤

最佳答案

您可以绕过所有额外的操作并使用np.repeat:

>>> np.repeat(['20', '35', '40', '10', '15'], [3, 2, 4, 2, 3])
array(['20', '20', '20', '35', '35', '40', '40', '40', '40',
       '10', '10', '15', '15', '15'], dtype='<U2')

如果您需要dtype=object,请先将第一个参数放入数组:

arr1 = np.array(['20', '35', '40', '10', '15'], dtype=object)
np.repeat(arr1, [3, 2, 4, 2, 3])

关于python - Numpy/展平列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72807933/

相关文章:

python - 我能否找出一个 numpy 向量是否显示为另一个向量的切片?

Python 断言不工作 : limit user enter only stated numbers but assert not working

Python 3 语法更改

python - 在python中计算文件的crc

Python 3.2 在 csv.DictReader 中跳过一行

python - 使用 F2PY 的可调节 Fortran 数组

python - 查找图像中的第一个非零值

python - 在 python 列表中抓取唯一的元组,不管顺序如何

python - 合并 2 个带有时间戳的 numpy 数组

python - 使用逻辑索引从二维数组中提取子数组 - python