我有一些代码通过嵌套循环运行。我猜有一种更"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 术语表):
for tuple in listOfTuples:
直接遍历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
*_
捕获 listOfTuples
中元组前两个元素之后的内容(假设我们想要的只是前两个元素)。
请注意,我使用 item.name
而不是 item.getName
。 Python 通常不关心 getter 和 setter,因为没有真正的私有变量概念。