numpy /弄平列表
我创建了这个字符
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数组的步骤
I have create this of character
list1 = [['20']*3,['35']*2,['40']*4,['10']*2,['15']*3]
result :
[['20', '20', '20'], ['35', '35'], ['40', '40', '40', '40'], ['10', '10'], ['15', '15', '15']]
I can convert it into a single list using list comprehension
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']
I was wondering how to do that with numpy
listNP=np.array(list1)
gives as output :
array([list(['20', '20', '20']), list(['35', '35']),
list(['40', '40', '40', '40']), list(['10', '10']),
list(['15', '15', '15'])], dtype=object)
The fact is that listNP.flatten() gives as an output the same result. Probably I missed a step when converting the list into an numpy array
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以绕过所有额外的操作,并使用
np.repeat
:如果您需要
dtype = object
,请首先将第一个参数放入数组:You can bypass all the extra operations and use
np.repeat
:If you need
dtype=object
, make the first argument into an array first:使用
hstack()
试图构建您的< code> listnp 带有
np.array
与您在OP中所做的那样,我对锯齿阵列有一个警告,不得不使用dtype = object
,但是让<代码> hstack 直接构建它不会引起警告(感谢评论中的@michael delgado)Use
hstack()
In trying to construct your
ListNP
withnp.array
as you do in the OP, I got a warning about jagged arrays and having to usedtype=object
, but lettinghstack
construct it directly doesn't evoke a warning (thanks @Michael Delgado in the comments)