迭代不同长度列表中的所有列表

编程入门 行业动态 更新时间:2024-10-05 19:19:49
本文介绍了迭代不同长度列表中的所有列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个列表列表.它看起来像这样:

I have a list of lists. It looks something like this:

[ [4,7,9,10], [5,14,55,24,121,56, 89,456, 678], [100, 23, 443, 34, 1243,] .... ]

我想进行迭代,以便在每次迭代时从所有列表中获取该索引的相应元素,如果列表为空,则将其删除.

I want to iterate such that on every iteration I get the respective element of that index from all lists and if the list gets empty, drop it.

例如,当索引为 0 时,我想要一个列表,该列表将从列表 0 中扩展(添加)4,从列表 1 中扩展(添加)5,从列表 2 中扩展(添加)100(所有列表的第 0 个索引)并且如果列表为空(像列表 0 在第 3 次迭代后将被完全覆盖,跳过它.所以迭代应该跳过这个列表并移动到下一个列表.

For instance, when index will be 0, I want a list that would extend (add) 4 from list 0,5 from list 1, 100 from list 2 (0th index of all list) and if the list gets empty (like list 0 will be fully covered after 3rd iteration, skip it. So iteration should skip this list and move on the next list.

所以输出应该是这样的:[4,5,100, 7, 14, 23, 9, 55, 443, 10, 24, 34, 121, 1243, 56. 89, 456, 678]

So the output should look like: [4,5,100, 7, 14, 23, 9, 55, 443, 10, 24, 34, 121, 1243, 56. 89, 456, 678]

我想要一个扩展这些值的列表.

I want a list that extends these values.

推荐答案

zip_longest 是有问题的,因为如果 fillvalue 出现在输入(这可以解决,但它总是会有点hacky).

zip_longest is problematic, since any solution would silently drop the fillvalue if it occurs in the inputs (this can be worked around, but it's always going to be a little hacky).

最通用的解决方案是 roundrobin 配方noreferrer">itertools 模块:

The most general solution is the roundrobin recipe from the itertools module:

from itertools import cycle, islice def roundrobin(*iterables): "roundrobin('ABC', 'D', 'EF') --> A D E B F C" # Recipe credited to George Sakkis num_active = len(iterables) nexts = cycle(iter(it).__next__ for it in iterables) while num_active: try: for next in nexts: yield next() except StopIteration: # Remove the iterator we just exhausted from the cycle. num_active -= 1 nexts = cycle(islice(nexts, num_active))

对于您的输入,您可以执行以下操作:

For your input, you'd do something like:

mylist = [ [4,7,9,10], [5,14,55,24,121,56, 89,456, 678], [100, 23, 443, 34, 1243,] .... ] print(list(roundrobin(*mylist)))

更多推荐

迭代不同长度列表中的所有列表

本文发布于:2023-11-29 15:33:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646807.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:长度   迭代   列表   列表中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!