[英]Unpack lists that are elements of a np.array in Python
Anybody know how I can "unpack" lists which are elements/cells of a np.array?有谁知道我如何“解压缩”作为 np.array 元素/单元格的列表? This is what the output looks like now:这就是输出现在的样子:
[[0 301227 0.863 0.456 -3.551 0.532 135.96200000000002 4
list([0.49, 0.33, 0.33, 0.28, 0.26, 0.47, 0.28, 0.29, 0.41, 0.42, 0.85, 0.48])
list([53.09, 119.1, 36.67, -1.91, 11.38, -20.86, -0.56, 4.01, -3.51, 0.9, -8.72, 1.04])
66.66666666666667 1.0]]
I want to unpack those lists so that each value is just another item/column in my array.我想解压缩这些列表,以便每个值只是数组中的另一个项目/列。 I can also make the lists into np.arrays if that helps.如果有帮助,我也可以将列表放入 np.arrays 中。 Should be an easy fix, I just haven't found it yet.应该很容易解决,我只是还没有找到它。
Cheers干杯
If I understood your question correctly, you can use numpy.concatenate() for that:如果我正确理解您的问题,您可以使用 numpy.concatenate() :
list = np.concatenate(input_list).ravel()
If you want the output to be in list form, you can append .tolist()
如果您希望输出为列表形式,您可以附加.tolist()
I think I understand your issue a little better now.我想我现在更了解你的问题了。 I created something to try and match the situation you're facing, and it returns a list where every item inside every list becomes just another item as you wanted:我创建了一些东西来尝试匹配您所面临的情况,它返回一个列表,其中每个列表中的每个项目都变成了您想要的另一个项目:
import numpy as np
input_list = [0, 2, 4, 1, 5,np.array([1, 2, 3]), 6, 1, 6, 1, 2, np.array([1, 2, 3])]
def flatten(l):
for item in l:
try:
yield from flatten(item)
except TypeError:
yield item
output_list = list(flatten(input_list)))
Output is: [0, 2, 4, 1, 5, 1, 2, 3, 6, 1, 6, 1, 2, 1, 2, 3]
输出为: [0, 2, 4, 1, 5, 1, 2, 3, 6, 1, 6, 1, 2, 1, 2, 3]
Tested it with np arrays and list as well, should have no problems.也用 np 数组和列表对其进行了测试,应该没有问题。 Also, I didn't create the output list as a np.array, but you can easily change it to do so if you wish此外,我没有将输出列表创建为 np.array,但是如果您愿意,您可以轻松地更改它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.