简单地说,我有一个server
类的列表,其中包含component
类的列表,其中包含function
类的列表。您会看到它的去向。
在我的程序中,我想从每个函数类中检索一个值,然后互相使用所有这些值,然后将结果值加回到function
类中。我最终一遍又一遍地使用嵌套循环。
这是我的代码:
component_subscriptions = {}
for server in self.network.servers:
for component in server.components:
for function in component.functions:
component_subscriptions[function.name] = []
for server in self.network.servers:
for component in server.components:
for function in component.functions:
for subscription in function.subscriptions:
if subscription.name in component_subscriptions.keys():
component_subscriptions[subscription.name].append(function.publish_address)
for server in self.network.servers:
for component in server.components:
for function in component.functions:
print(function.name)
if function.name in component_subscriptions.keys():
function.subscribers.extend(component_subscriptions[function.name])
for server in self.network.servers:
for component in server.components:
for function in component.functions:
if function.name in component_subscriptions.keys():
function.subscribers = component_subscriptions[function.name]
有没有一种方法可以重新使用por来简化三深for循环?我是否错过了一些荒谬的显而易见的事情?
答案 0 :(得分:2)
使用生成器的直接方法:
def gen_functions(self):
for server in self.network.servers:
for component in server.components:
for function in component.functions:
yield function
for function in gen_functions(self):
component_subscriptions[function.name] = []
for function in gen_functions(self):
for subscription in function.subscriptions:
if subscription.name in component_subscriptions.keys():
component_subscriptions[subscription.name].append(function.publish_address)
...
关于第二个循环,我更喜欢这样:
for function in gen_functions(self):
for subscription in (component_subscriptions[s.name] for s in function.subscriptions if s.name in component_subscriptions):
subscription.append(function.publish_address)
要重用它,请创建另一个函数:
def iter_function_subscriptions(function):
for subscription in (component_subscriptions[s.name] for s in function.subscriptions if s.name in component_subscriptions):
yield subscription
所以现在将它们结合起来
for function in gen_funtions(self):
for subscription in iter_function_subscriptions(function):
subscriptoin.append(function.publish_address)
已完成,但是您可能需要将它们添加到函数类中。
# patching the class. it will be better if you can directly add this method into function class
type(function).iter_subscriptions = iter_function_subscriptions
然后
for function in gen_funtions(self):
for subscription in function.iter_subscriptions():
subscription.append(function.publish_address)