将嵌套列表的元素均值插入到同一列表中

问题描述 投票:0回答:1

假设有一个嵌套的浮点列表

L = [[a,b,c],[e,f,g],[h,i,j]]

我可以定义什么样的函数来迭代列表一次并将每个连续列表的元素的平均值插入到同一个列表中?即我想得到

L1 = [[a,b,c],[(a+e)/2,(b+f)/2,(c+g)/2],[e,f,g],[(e+h)/2,(f+i)/2,(g+j)/2],[h,i,j]]

我知道获取元素的功能意味着两个列表:

from operator import add
new_list = list(map(add,list1,list2))
J = [j/2 for j in new_list]

然而,将这个平均值列表插回到同一列表中,同时通过旧列表保持正确的索引迭代证明是具有挑战性的。

python list nested-lists
1个回答
1
投票

有两种情况:

  1. 您不关心结果列表是否是相同的列表:
new_list = []
for i in range(len(L)-1):
    new_list.append(L[i])
    new_list.append(list(map(lambda x: sum(x)/len(x), zip(L[i],L[i+1]))))
new_list.append(L[-1])
  1. 您希望更改就地完成:
i=0
while i < len(L)-1:
    new_elem = list(map(lambda x: sum(x)/len(x), zip(L[i],L[i+1])))
    L.insert(i+1, new_elem)
    i += 2

编辑:如果您使用的是python 3.4或更高版本,而不是lambda x: sum(x)/len(x),您可以使用mean(x)(来自包statistics)。

© www.soinside.com 2019 - 2024. All rights reserved.