将嵌套列表的逐元素平均值插入同一个列表
Inserting the element-wise mean of nested list into the same list
假设有一个嵌套的浮动列表列表
L = [[a,b,c],[e,f,g],[h,i,j]]
我可以定义什么样的函数来遍历列表一次并将每个连续列表的元素的平均值插入同一个列表? IE。我想得到
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]
然而,将这个平均值列表插入回同一个列表,同时通过旧列表维护正确的索引迭代被证明具有挑战性。
有两种情况:
- 你不关心结果列表是否是同一个列表:
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])
- 您希望就地完成更改:
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 或更高版本,您可以使用 mean(x)
(来自包 statistics
)而不是 lambda x: sum(x)/len(x)
。
假设有一个嵌套的浮动列表列表
L = [[a,b,c],[e,f,g],[h,i,j]]
我可以定义什么样的函数来遍历列表一次并将每个连续列表的元素的平均值插入同一个列表? IE。我想得到
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]
然而,将这个平均值列表插入回同一个列表,同时通过旧列表维护正确的索引迭代被证明具有挑战性。
有两种情况:
- 你不关心结果列表是否是同一个列表:
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])
- 您希望就地完成更改:
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 或更高版本,您可以使用 mean(x)
(来自包 statistics
)而不是 lambda x: sum(x)/len(x)
。