[英]How to get all iterations of a list of lists?
Let's say I have the list:假设我有清单:
a = [[1,2], [3,4,5], [6,7,8,9]]
I'm looking to get all of the iterations of the list like this:我希望像这样获得列表的所有迭代:
[[1], None, None]
[[1,2], None, None]
[[1,2], [3], None]
[[1,2], [3,4], None]
[[1,2], [3,4,5], None]
[[1,2], [3,4,5], [6]]
[[1,2], [3,4,5], [6,7]]
[[1,2], [3,4,5], [6,7,8]]
[[1,2], [3,4,5], [6,7,8,9]]
With the final output being a list of those iterations:最终输出是这些迭代的列表:
result = [[[1], None, None], [[1,2], None, None], ... , [[1,2], [3,4,5], [6,7,8,9]]]
You can use a list comprehension:您可以使用列表理解:
a = [[1,2], [3,4,5], [6,7,8,9]]
new_a = [a[:i]+[b[:k]]+[None]*(len(a)-i-1) for i, b in enumerate(a) for k in range(len(b)+1) if b[:k]]
Output:输出:
[[[1], None, None],
[[1, 2], None, None],
[[1, 2], [3], None],
[[1, 2], [3, 4], None],
[[1, 2], [3, 4, 5], None],
[[1, 2], [3, 4, 5], [6]],
[[1, 2], [3, 4, 5], [6, 7]],
[[1, 2], [3, 4, 5], [6, 7, 8]],
[[1, 2], [3, 4, 5], [6, 7, 8, 9]]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.