如何递归更新列表

问题描述 投票:8回答:4

我有一个dicts列表:

a = [{'one': 1}, {'two': 2}, {'three': 3}, {'four': 4}, {'five': 5}]

我想用所有余数的总和更新此列表中每个元素的值。 (所以'one'将获得值2+3+4+5)。

所以它看起来像这样:

a = [{'one': 14}, {'two': 12}, {'three': 9}, {'four': 5}, {'five': 5}]

'five'是最后一个,所以它不会更新。

我不知道如何实现这一目标。我认为你构造一个函数,将自己称为recursivly类似于:

def recursive(a):
   if len(a) == 1:
      return list(a[0].values())[0]
    else:
      val = list(a[0].values())[0]
      return val + recursive(a.pop(0))

但我不确定这样做list(a[0].values())[0]是“最好的”方式。这也是一个KeyError: 0

有任何想法吗?

python
4个回答
7
投票

迭代和就地解决方案

a = [{'one': 1}, {'two': 2}, {'three': 3}, {'four': 4}, {'five': 5}]
sum_so_far = 0
first_flag = False
for i in a[::-1]:
    k,v = i.items()[0]   #For Python 3 k,v = list(i.items())[0]
    sum_so_far += v
    if first_flag:
        i[k] = sum_so_far # do not change the value at first

    first_flag=True

产量

[{'one': 15}, {'two': 14}, {'three': 12}, {'four': 9}, {'five': 5}]

3
投票

你的问题来自a.pop(0)的输出。 A.pop(0)返回0处的元素,而不是没有元素为0的列表。因此,当您以递归方式调用时,您将对dict而不是列表进行索引。您期望输入递归调用的内容是什么?

我猜你试图删除第0个索引,然后递归调用。去做这个,

a.pop(0);
return val + recursive(a)

编辑:注释 - 键错误0表示当键0不存在时,您使用键0为dict编制索引。


0
投票

快速而肮脏的一个衬垫......

[{list(d.keys())[0]: sum(list(v.values())[0] for v in a[i + (1 if i<len(a)-1 else 0):])} for i, d in enumerate(a)]

# [{'one': 14}, {'two': 12}, {'three': 9}, {'four': 5}, {'five': 5}]

0
投票

一种可能的递归解决方案:

d = [{'one': 1}, {'two': 2}, {'three': 3}, {'four': 4}, {'five': 5}]
def sums(data, _sum = 0):
  a, *b = data
  if not b:
    return [a], list(a.values())[0]
  c, _d = sums(b, _sum+list(a.values())[0])
  return [{list(a.keys())[0]:_d}, *c], _d+list(a.values())[0]

result, _ = sums(d)

输出:

[{'one': 14}, {'two': 12}, {'three': 9}, {'four': 5}, {'five': 5}]
© www.soinside.com 2019 - 2024. All rights reserved.