如何以惯用/功能方式编写此代码?

问题描述:

我试着写这篇文章的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) 

我不太喜欢这个解决方案。

  1. 它比第一个没有更多的可读性。
  2. 它遍历列表3次而不是一次。

我有种想是分成3路流,每个被映射,然后它们合并到同一数据流并得到变成一个字典(我希望这句话是有道理的)

请分享你的想法这个...

+7

工作代码批判请求应在https://codereview.stackexchange.com/ – wwii

+0

张贴在现实中,如果我写了这个,我可能会做它的第一种方式。但是如果我想要看起来,我会设置一个将属性值映射到函数的字典。类似于'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表达式。主要观点是函数只是对象,可以像其他任何字符一样在字典中查找。 –

+0

“更多功能”并不一定意味着“更习惯”,“更模块化”或“更可重用”。你为什么首先要用功能性工具? – user2357112

你可以有刚刚选择的值进入词典,而不是修改字典的功能:

def value(item): 
    if item.attribute == 'foo': 
     return [func(x) for x in item.attribute2] 
    elif item.attribute == 'bar': 
     return [] 
    else: 
     return [func2(x) for x in item.attribute3] 

然后你就可以创建字典ionary声明:

items = get_items() 

dic = {item.name: value(item) 
     for item in items}