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)))
这篇关于迭代不同长度列表中的所有列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:迭代不同长度列表中的所有列表


基础教程推荐
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 筛选NumPy数组 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01