简体   繁体   English

Python 中的列表排序(转置)

[英]Lists sorting in Python (transpose)

I have arbitrary lists, for instance here are three lists:我有任意列表,例如这里有三个列表:

a = [1,1,1,1]
b = [2,2,2,2]
c = [3,3,3,3]

And I want transpose them together in order to get the output like this:我想将它们转置在一起以获得这样的输出:

f_out = [1,2,3]
g_out = [1,2,3]
...
n_out = [1,2,3]

As, you can see, I just converted "columns" to "rows".正如你所看到的,我只是将“列”转换为“行”。

The issue is a solution has to be independent of the lists length.问题是解决方案必须独立于列表长度。

For example:例如:

a = [1,1]
b = [2]
c = [3,3,3]
# output
f_out = [1,2,3]
g_out = [1,3]
n_out = [3]

You can use zip_longest您可以使用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]

If None is a potential valid value in the lists, use a sentinel object instead of the default None :如果None是列表中的潜在有效值,请使用哨兵对象而不是默认的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]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM