python - Python 中的列表排序(转置)

标签 python list python-3.x sorting transpose

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

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/

相关文章:

python - 从 Python 调用时 SQL 存储过程未完成

python - 从给定内容开始的 HTML 表格单元格内容的 XPath

python - 如何测试 Python 对象是否是模块?

python - 如何为使用 ImageGrid 创建的整个图形创建单轴标签

java - 参数化接口(interface)可以是子接口(interface)吗?

C# - 遍历 List<T> 中的给定类型元素

python - 在Python中循环写入命令以分别从列表中输出许多不同的索引

python - 使用 Python 3.6.1 在 Linux/Intel Xeon 上使用 "fork"上下文 block 进行多处理?

python-3.x - 如果不为空,Pandas 使用值,否则使用下一列中的值

python - 在 "for line in data"循环中使用 .readline() 将文件的多行分配给多个变量