Iterate over all lists inside a list of varied lengths(迭代不同长度列表中的所有列表)
问题描述
我有一个列表列表.它看起来像这样:
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)))
这篇关于迭代不同长度列表中的所有列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:迭代不同长度列表中的所有列表
基础教程推荐
- 对多索引数据帧的列进行排序 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
