gpt4 book ai didi

python - 有没有比迭代相同循环更好的方法来检索值?

转载 作者:行者123 更新时间:2023-12-01 00:58:26 24 4
gpt4 key购买 nike

简单来说,我有一个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]

有没有办法重用或简化三层for循环?我是否遗漏了一些明显可笑的东西?

最佳答案

使用生成器的直接方法:

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)

关于python - 有没有比迭代相同循环更好的方法来检索值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56039192/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com