Python - 使用 numpy 转置列表(不同长度的行)失败

标签 python numpy transpose

<分区>

当列表仅包含长度相同的行时,转置有效:

numpy.array([[1, 2], [3, 4]]).T.tolist();
>>> [[1, 3], [2, 4]]

但是,在我的例子中,列表包含不同长度的行:

numpy.array([[1, 2, 3], [4, 5]]).T.tolist();

失败了。有什么可能的解决方案吗?

最佳答案

如果您没有将 numpy 作为强制要求,您可以使用 itertools.zip_longest进行转置:

from itertools import zip_longest

l = [[1, 2, 3], [4, 5]]
r = [list(filter(None,i)) for i in zip_longest(*l)]
print(r)
# [[1, 4], [2, 5], [3]]
由于 不匹配 长度,

zip_longestNone 填充结果,因此列表理解和 filter(None, ... ) 用于删除 None

在 python 2.x 中它将是 itertools.izip_longest

关于Python - 使用 numpy 转置列表(不同长度的行)失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38466460/

相关文章:

python - 有没有办法加快 numpy.where 的循环?

excel - SAS proc转置并输出到excel

c - 使用一个 for 循环就地转置矩阵

sql - 如何转置 SQLite 中的表?

python - (Gensim) 带有 alpha 参数的 ValueError : invalid shape,

python - 成员资格测试中的 numpy dtype 给出了奇怪的结果

python - Clojure 与 Numpy 中的矩阵乘法

python - 如何选择 pandas 中一组的最后一行?

python - ndb 异步 "yield next"消费 get_multi 异步

python - 如何在具有偶数个条目的numpy掩码数组中获得单个中位数