如何以惯用的/函数式的方式编写此代码?

2024-04-23 06:47:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图以一种更模块化/可重用的方式编写这段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次而不是1次。你知道吗

我想要的是一个流,分成3条路径,每一条路径都被映射,然后它们合并回同一个流,变成一个dict(我希望这句话有意义)

请分享你的想法。。。你知道吗


Tags: lambdanameinreduceforfoobarupdate
1条回答
网友
1楼 · 发布于 2024-04-23 06:47:24

您可以使用一个函数,它只选择要进入字典的值,而不是修改字典:

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]

然后可以声明性地创建字典:

items = get_items()

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

相关问题 更多 >