我有以下的多回路情況:我們如何使用理解這裏
notify=dict()
for m in messages:
fields=list()
for g in groups:
fields.append(func(g,m))
notify[m.name]=fields
return notify
是否有寫下面的理解或地圖的方式,那樣會更好看(希望有更好的表現太)
我有以下的多回路情況:我們如何使用理解這裏
notify=dict()
for m in messages:
fields=list()
for g in groups:
fields.append(func(g,m))
notify[m.name]=fields
return notify
是否有寫下面的理解或地圖的方式,那樣會更好看(希望有更好的表現太)
假設你真的是通知所有累積的結果
return {m.name: [func(g, m) for g in groups] for m in messages}
這非常有趣。是否有排除func()返回None的情況的方法。我不需要將這些情況添加到字典中。 – IUnknown
@IUnknown,你的意思是,當一個特定的'm'的所有'func()'返回None時,還是僅僅爲了壓制它從單個列表中? –
from itertools import product
results = [func(g,m) for m,g in product(messages,groups)]
編輯
我想你可能真的想類型的字典詞典,而不是列表的字典:
from collections import defaultdict
from itertools import product
results = defaultdict(dict)
for m,g in product(messages,groups):
results[m.name][g] = func(g,m)
或照搬gnibbler:
return {m.name: {g:func(g,m) for g in groups} for m in messages}
現在你可以使用results[msgname][groupname]
得到的func(g,m)
值。
難道你不想讓字典被返回嗎?如下(假設m的字段名)
notify={m.name:[func(g,m) for g in groups] for m in messages}
不使用解析,但簡化了你的代碼位。
from collections import defaultdict
def foo(messages, groups):
notify=defaultdict(list)
for m in messages:
for g in groups:
notify[m.name].append(func(g,m))
return notify
這裏'結果'的含義是什麼,只需要嵌套循環中的最後一個值?它應該是'result.append'嗎? – jamylak
修改了代碼以提及意圖 – IUnknown
您是否打算在每個循環中創建一個新的'notify'? –