0
我試着寫這篇文章的Python代碼更模塊化/可重複使用的方式和我無法寫它如何以慣用/功能方式編寫此代碼?
考慮一下:
lst = get_list_of_objects()
dic = {}
for item in lst:
if item.attribute == 'foo':
dic[item.name] = [func(x) for x in item.attribute2]
elif item.attribute == 'bar':
dic[item.name] = []
else:
dic[item.name] = [func2(x) for x in item.attribute3]
我在嘗試使這個「功能」 :
fooItems = reduce(lambda dic, item: dic.update(item.name, map(func, item.attribute2)),
filter(lambda i: i.attribute == 'foo', lst),
{})
barItems = reduce(lambda dic, item: dic.update(item.name, []),
filter(lambda i: i.attribute == 'bar', lst),
fooItems)
dic = reduce(lambda dic, item: dic.update(item.name, map(func2, item.attribute3)),
filter(lambda i: i.attribute != ('bar' or 'foo'), lst),
barItems)
我不太喜歡這個解決方案。
- 它比第一個沒有更多的可讀性。
- 它遍歷列表3次而不是一次。
我有種想是分成3路流,每個被映射,然後它們合併到同一數據流並得到變成一個字典(我希望這句話是有道理的)
請分享你的想法這個...
工作代碼批判請求應在https://codereview.stackexchange.com/ – wwii
張貼在現實中,如果我寫了這個,我可能會做它的第一種方式。但是如果我想要看起來,我會設置一個將屬性值映射到函數的字典。類似於'dic = {item.name:funcs.get(item.attribute,lambda _:[])(item)}'funcs = {'foo':lambda item:[func(x)for x in item .attribute2],'bar':lambda項目:[func2(x)for item.attribute3]}。除了更好的名稱,我可能會考慮實際給出函數名稱,而不是隨處使用lambda表達式。主要觀點是函數只是對象,可以像其他任何字符一樣在字典中查找。 –
「更多功能」並不一定意味着「更習慣」,「更模塊化」或「更可重用」。你爲什麼首先要用功能性工具? – user2357112