我有一个二维 python 数组,如下所示:
A = [[186,192,133],[12],[122,193,154],[166,188,199],[133,44,23,56,78,96,100]]
现在如何制作一个看起来像这样的新数组?
B = [[186,12,122,166,133],[192, 193,188,44],[133,154,199,23],[56],[78],[96],[100]]
我基本上想将 A 的列转换为 B 的行。
请您参考如下方法:
解决方案
from itertools import izip_longest # in Python 3 zip_longest
list([x for x in y if x is not None] for y in izip_longest(*A))
结果:
[[186, 12, 122, 166, 133],
[192, 193, 188, 44],
[133, 154, 199, 23],
[56],
[78],
[96],
[100]]
解释
izip_longest 给你一个迭代器:
>>> from itertools import izip_longest
>>> izip_longest([1, 2, 3], [4, 5])
<itertools.izip_longest at 0x103331890>
将它转换成一个列表,看看它做了什么:
>>> list(izip_longest([1, 2, 3], [4, 5]))
[(1, 4), (2, 5), (3, None)]
它从每个列表中取出一个元素,并将它们成对放入一个元组中。此外,它用 None(或您提供的其他值)填充缺失值。
* 允许为函数提供未指定数量的参数。例如,我们可以将我们的两个列表放在另一个列表中并使用 * 并且它仍然有效:
>>> list(izip_longest(*[[1, 2, 3], [4, 5]]))
[(1, 4), (2, 5), (3, None)]
这不限于两个参数。三个示例。
单个参数:
>>> list(izip_longest([1, 2, 3], [4, 5], [6]))
[(1, 4, 6), (2, 5, None), (3, None, None)]
* 列表中的所有参数:
>>> list(izip_longest(*[[1, 2, 3], [4, 5], [6]]))
[(1, 4, 6), (2, 5, None), (3, None, None)]
您不需要 None 值。用列表理解过滤掉它们:
>>> [x for x in y if x is not None]
对于您的A,您会得到:
>>> list(izip_longest(*A))
[(186, 12, 122, 166, 133),
(192, None, 193, 188, 44),
(133, None, 154, 199, 23),
(None, None, None, None, 56),
(None, None, None, None, 78),
(None, None, None, None, 96),
(None, None, None, None, 100)]
现在,y 遍历此列表中的所有条目,例如 (186, 12, 122, 166, 133)。 x 遍历 y 中的每个数字,例如 186。外部 [] 创建一个列表。所以不是元组 (186, 12, 122, 166, 133) 我们得到一个列表 [186, 12, 122, 166, 133]。最后,if x is not None 过滤掉 None 值。
