python - 有没有更好的方法来迭代 python 中的嵌套循环

标签 python algorithm python-3.x optimization

我有一些通过嵌套循环运行的代码。我猜想有一种更“pythonic”的方式来做到这一点。有什么建议么?

代码的基本部分如下所示:

   for e in range(len(listOfTuples)):

        for item in self.items:
            if item.getName() == listOfTuples[e][0]:
                <do stuff>
            if item.getName() == listOfTyples[e][1]:
                <do other stuff>
                continue

        if <both above if statements got answers>:
            <do yet more stuff>

有没有更好的方法来编写这些嵌套循环?

最佳答案

您可以使用生成器函数。至少它向您隐藏了嵌套 for 循环的“丑陋之处”。

def combine_items_and_tuples(items, listOfTuples):
   for e in range(len(listOfTuples)):
        for item in items:
            yield e, item

简单地调用它:

for e, item in combine_items_and_tuples(self.items, listOfTuples):
      if item.getName() == listOfTuples[e][0]:
                <do stuff>
      if item.getName() == listOfTyples[e][1]:
                <do other stuff>
                continue

      if <both above if statements got answers>:
            <do yet more stuff>

正如评论中已经提到的,您还可以直接迭代 listOfTuples,因为它是可迭代的(在 python glossary 中查看):

for tuple in listOfTuples:

关于python - 有没有更好的方法来迭代 python 中的嵌套循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46852090/

相关文章:

python - GridSearchCV 初始化

python - 如何使用 Python 将专辑封面嵌入到 MP3 中?

python - 提取 numpy 数组中每个元素的最后两位数字的有效方法

python-3.x - 将两列的乘积连续添加到一列的累积和中

python-3.x - 创建实例失败时调用的析构函数?

python - 如何从 avro 架构 (.avsc) 创建表?

c - 层次树打印所有后缀提供错误的输出

c++ - 生成从 1 到 n 的 k 个数字的 nCk 组合的程序

python - Python 中的 Hopcroft–Karp 算法

python - 如何在 matplotlib python 中设置确切的日期刻度