我有任意列表,例如这里有三个列表:
a = [1,1,1,1]
b = [2,2,2,2]
c = [3,3,3,3]
我想将它们转置在一起以获得这样的输出:
f_out = [1,2,3]
g_out = [1,2,3]
...
n_out = [1,2,3]
如您所见,我只是将“列”转换为“行”。
问题是解决方案必须独立于列表长度。
例如:
a = [1,1]
b = [2]
c = [3,3,3]
# output
f_out = [1,2,3]
g_out = [1,3]
n_out = [3]
最佳答案
您可以使用 zip_longest
>>> from itertools import zip_longest
>>> a = [1,1]
>>> b = [2]
>>> c = [3,3,3]
>>> f,g,h=[[e for e in li if e is not None] for li in zip_longest(a,b,c)]
>>> f
[1, 2, 3]
>>> g
[1, 3]
>>> h
[3]
如果 None
是列表中的潜在有效值,请使用标记 object而不是默认的 None
:
>>> b = [None]
>>> sentinel = object()
>>> [[e for e in li if e is not sentinel] for li in zip_longest(a,b,c, fillvalue=sentinel)]
[[1, None, 3], [1, 3], [3]]
关于python - Python 中的列表排序(转置),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33875422/