我有一个像这样的压缩对象:
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
flattenalways returns a copy andravelreturns 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 fromflattenthis will never happen.ravelwill often be faster since no memory is copied, but you have to be more careful about modifying the array it returns.
