gpt4 book ai didi

python - 如何将包含嵌套数组的压缩对象展平到列表中?

转载 作者:太空宇宙 更新时间:2023-11-04 08:48:41 26 4
gpt4 key购买 nike

我有一个像这样的压缩对象:

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))

但是当我打印时数组仍然存在。

我做错了什么?

最佳答案

使用其中之一

这是一个 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]

关于ravelflatten的区别,摘自What is the difference between flatten and ravel functions in numpy? ,

The difference is that flatten always returns a copy and ravel returns a view of the original array whenever possible. This isn't visible in the printed output, but if you modify the array returned by ravel, it may modify the entries in the original array. If you modify the entries in an array returned from flatten 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com