我有一些通过嵌套循环运行的代码。我猜想有一种更“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/