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

标签 python list python-3.x numpy

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

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/

相关文章:

Python Scrapy : TypeError: to_bytes must receive a unicode, str 或 bytes 对象,得到 int

python-3.x - 使用 chrome canary 执行 selenium python 脚本时如何抑制控制台错误/警告/信息消息

django - 如何使用 Django ModelForm 生成下拉输入?

python-3.x - python3中的urllib异常处理

java - 如何创建将 List<List<Integer>> 和 List<List<Double>>(可能更多)转换为字符串的函数?

python - 如何使用递归计算嵌套列表的最大长度?

python - 使用 unravel_index 查找最大数字的索引

python - 一个Python包的多种安装配置

python - 由于编码而比较哈希值时出错

java - Hibernate原生查询返回List对象列表