gpt4 book ai didi

python - 如何在 python 中使用不相等的子列表进行列表理解

转载 作者:太空狗 更新时间:2023-10-29 20:16:26 25 4
gpt4 key购买 nike

我有一个不相等列表的列表。我想通过子列表的列表理解生成一个新列表。

s = [['a','b','c','d'],['e','f','g'],['h','i'],['j','k','l','m']]

我正在尝试以下代码,但它不断引发 indexError:

new_s = []
for i in range(len(s)):
new_s.append((i,[t[i] for t in s if t[i]))

预期的输出是:

new_s = [(0,['a','e','h','j']),(1,['b','f','i','k']),(2,['c','g','l']),(3,['d','m'])]

有什么想法可以让它发挥作用吗?

最佳答案

您可以使用 itertools.zip_longest以元素方式遍历每个子列表,同时使用 None 作为较短子列表的填充值。

然后使用filter删除填充中使用的 None 值。

所以所有的东西都放在一个列表推导中:

>>> from itertools import zip_longest
>>> [(i, list(filter(None, j))) for i, j in enumerate(zip_longest(*s))]
[(0, ['a', 'e', 'h', 'j']), (1, ['b', 'f', 'i', 'k']), (2, ['c', 'g', 'l']), (3, ['d', 'm'])]

关于python - 如何在 python 中使用不相等的子列表进行列表理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49176943/

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