我创造了这个角色
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/