简体   繁体   中英

How to write this code in a idiomatic/functional way?

I'm trying to write this piece of python code in a more modular/reusable fashion and I'm having trouble writing it

Consider this:

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]

My attempt at making this "functional":

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)

I don't really like this solution that much.

  1. It's not much more readable than the first one.
  2. It iterates over the list 3 times instead of one.

What i kind of want is a stream that splits into 3 paths, each gets mapped on and then they merge back into the same stream and get turned into a dict (I hope this sentence makes sense)

Please share your thoughts about this...

You can have a function which just chooses the value to go into the dictionary, rather than modifying the dictionary:

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]

Then you can create the dictionary declaratively:

items = get_items()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM