我有一个像这样的压缩对象:
z = zip(a, b)
lst = list(z)
print(lst)
输出:
[(0, array([[72, 65],
[70, 71]], dtype=uint8)),
(1, array([[ 71, 99],
[190, 163]], dtype=uint8)),
(2, array([[52, 59],
[69, 72]], dtype=uint8)), etc...
我想将此列表展平为以下内容:
[0, 72, 65, 70, 71, 1, 71, 99, 190, 163, 2, 52, 59 etc..]
我试过用
y = sum(w, ())
# or
y = list(itertools.chain(*lst))
但是当我打印时数组仍然存在。
我做错了什么?
最佳答案
使用其中之一
-
numpy.ravel
返回一个连续的展平数组。 -
numpy.ndarray.flat
返回数组上的一维迭代器。 (这是一个numpy.flatiter
实例) -
numpy.ndarray.flatten
返回折叠成一维数组的副本。
这是一个 MWE。
import numpy as np
lists = [(0, np.array([ [72, 65],
[70, 71]], dtype=np.uint8)),
(1, np.array([ [71, 99],
[190, 163]], dtype=np.uint8))]
l = list()
for idx, array in lists:
l.append(idx)
l.extend(np.ravel(array)) # returns a contiguous flattened array
#l.extend(array.flat) # return a 1-D iterator over the array.
#l.extend(array.flatten()) # return a copy of the array collapsed into one dimension
print(l)
# Output
[0, 72, 65, 70, 71, 1, 71, 99, 190, 163]
关于ravel
和flatten
的区别,摘自What is the difference between flatten and ravel functions in numpy? ,
The difference is that
flatten
always returns a copy andravel
returns a view of the original array whenever possible. This isn't visible in the printed output, but if you modify the array returned byravel
, it may modify the entries in the original array. If you modify the entries in an array returned fromflatten
this will never happen.ravel
will often be faster since no memory is copied, but you have to be more careful about modifying the array it returns.
关于python - 如何将包含嵌套数组的压缩对象展平到列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37534422/