Python中的列表排序(转置)

Pad*_*ddy 6 python sorting transpose list python-3.x

我有任意列表,例如这里有三个列表:

a = [1,1,1,1]
b = [2,2,2,2]
c = [3,3,3,3]
Run Code Online (Sandbox Code Playgroud)

我想将它们转换到一起以获得如下输出:

f_out = [1,2,3]
g_out = [1,2,3]
...
n_out = [1,2,3]
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我只是将"列"转换为"行".

问题是解决方案必须独立于列表长度.

例如:

a = [1,1]
b = [2]
c = [3,3,3]
# output
f_out = [1,2,3]
g_out = [1,3]
n_out = [3]
Run Code Online (Sandbox Code Playgroud)

daw*_*awg 11

你可以使用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]
Run Code Online (Sandbox Code Playgroud)

如果None是列表中的潜在有效值,请使用sentinel 对象而不是默认值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]]
Run Code Online (Sandbox Code Playgroud)

  • 它是python3的zip_longest (2认同)