一个接一个地迭代两个列表 [英] Iterating over two lists one after another

查看:172
本文介绍了一个接一个地迭代两个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列表 list1 list2 的数字,我想用相同的指令迭代它们。像这样:

I have two lists list1 and list2 of numbers, and I want to iterate over them with the same instructions. Like this:

for item in list1:
  print(item.amount)
  print(item.total_amount)

for item in list2:
  print(item.amount)
  print(item.total_amount)

但这感觉多余。我知道我可以为list1 + list2中的项目写,但它的运行时间价格。

But that feels redundant. I know I can write for item in list1 + list2:, but it has a price of running-time.

有没有办法没有松散的时间呢?

Is there a way do that without loose time?

推荐答案

这可以通过 itertools.chain

import itertools

l1 = [1, 2, 3, 4]
l2 = [5, 6, 7, 8]

for i in itertools.chain(l1, l2):
    print(i, end=" ")

将打印:

1 2 3 4 5 6 7 8 

根据文档,执行以下操作:

As per the documentation, chain does the following:


创建一个迭代器,从第一个迭代中返回元素,直到它耗尽,然后进入下一个迭代,直到所有的迭代都用尽。

Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted.

如果你有你的列表我na list, itertools.chain .from_iterable 可用:

If you have your lists in a list, itertools.chain.from_iterable is available:

l = [l1, l2]
for i in itertools.chain.from_iterable(l):
    print(i, end=" ")

产生相同的结果。

如果您不想为此导入模块,那么为它编写函数是相当的直截了当:

If you don't want to import a module for this, writing a function for it is pretty straight-forward:

def custom_chain(*it):
    for iterab in it:
        yield from iterab

这需要Python 3,对于Python 2,只需 yield 他们回来使用循环:

This requires Python 3, for Python 2, just yield them back using a loop:

def custom_chain(*it):
    for iterab in it:
        for val in iterab:
            yield val

除了之前的, Python 3.5 及其扩展的解压缩一般化,也允许s在列表文字中解压缩:

In addition to the previous, Python 3.5 with its extended unpacking generalizations, also allows unpacking in the list literal:

for i in [*l1, *l2]:
    print(i, end=" ")

虽然这比 l1 + l2 它仍构造一个然后被抛出的列表;只能作为最终解决方案。

though this is slightly faster than l1 + l2 it still constructs a list which is then tossed; only go for it as a final solution.

这篇关于一个接一个地迭代两个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆