[英]Is there a better way to iterate over nested loops in python
I have some code that is running through nested loops. 我有一些通过嵌套循环运行的代码。 I am guessing that there is a more "pythonic" way of doing this.
我猜想有一种更“ pythonic”的方式来做到这一点。 Any suggestions?
有什么建议么?
The basic section of code looks like this: 代码的基本部分如下所示:
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>
Is there a better way to write these nested loops? 有没有更好的方法来编写这些嵌套循环?
You can use a generator function. 您可以使用生成器功能。 At least it hides the "ugliness" of a nested for loop to you.
至少它对您隐藏了嵌套for循环的“丑陋”。
def combine_items_and_tuples(items, listOfTuples):
for e in range(len(listOfTuples)):
for item in items:
yield e, item
simply call it with: 只需调用它:
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>
As already mentioned in the comments, you can also iterate of the listOfTuples
directly, since it is iterable (have a look in the python glossary ): 正如评论中已经提到的,您也可以直接迭代
listOfTuples
,因为它是可迭代的(请在python 词汇表中查看):
for tuple in listOfTuples:
Iterate directly over the listOfTuples
and unpack the values we care about 直接遍历
listOfTuples
并解压缩我们关心的值
for a, b, *_ in listOfTuples:
a_check, b_check = False, False
for item in self.items:
if item.name == a:
#do stuff
a_check = True
if item.name == b:
#do stuff
b_check = True
if a_check and b_check:
#do more stuff
The *_
captures stuff past the first two elements of the tuples in listOfTuples
(Assuming all we want is the first two elements). *_
捕获listOfTuples
组的前两个元素之后的listOfTuples
(假设我们想要的只是前两个元素)。
Notice I use item.name
instead of item.getName
. 注意,我使用
item.name
而不是item.getName
。 Python generally doesn't care about getters and setters because there's no real concept of a private variable. Python通常不关心getter和setter,因为没有真正的私有变量概念。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.