gpt4 book ai didi

Python:将不均匀的行转为列

转载 作者:太空狗 更新时间:2023-10-30 01:49:11 26 4
gpt4 key购买 nike

我有一个包含奇数个元素的列表列表:

[['a','b','c'], ['d','e'], [], ['f','g','h','i']]

我在 Reportlab 中显示一个表,我想将它们显示为列。据我了解,RL 仅采用我上面的行形式的表(鸭嘴兽)数据。

我可以使用循环来进行切换,但我觉得有一个列表理解会更快、更符合 Pythonic。我还需要在用完元素的列中留出一个空格。

所需的产品将是:

[['a','d','','f'],['b','e','','g'],['c','','','h'],['','','','i']]

编辑:例子应该是字符串,而不是数字

感谢您的帮助!

最佳答案

itertools.izip_longest()采用 fillvalue 参数。在 Python 3 上,它是 itertools.zip_longest() .

>>> l = [[1,2,3], [4,5], [], [6,7,8,9]]
>>> import itertools
>>> list(itertools.izip_longest(*l, fillvalue=""))
[(1, 4, '', 6), (2, 5, '', 7), (3, '', '', 8), ('', '', '', 9)]

如果您确实需要子列表而不是元组:

>>> [list(tup) for tup in itertools.izip_longest(*l, fillvalue="")]
[[1, 4, '', 6], [2, 5, '', 7], [3, '', '', 8], ['', '', '', 9]]

当然这也适用于字符串:

>>> l = [['a','b','c'], ['d','e'], [], ['f','g','h','i']]
>>> import itertools
>>> list(itertools.izip_longest(*l, fillvalue=""))
[('a', 'd', '', 'f'), ('b', 'e', '', 'g'), ('c', '', '', 'h'), ('', '', '', 'i')]

它甚至是这样工作的:

>>> l = ["abc", "de", "", "fghi"]
>>> list(itertools.izip_longest(*l, fillvalue=""))
[('a', 'd', '', 'f'), ('b', 'e', '', 'g'), ('c', '', '', 'h'), ('', '', '', 'i')]

关于Python:将不均匀的行转为列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13893435/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com