【问题标题】:Inserting the element-wise mean of nested list into the same list将嵌套列表的元素均值插入同一个列表
【发布时间】:2019-03-28 11:08:20
【问题描述】:

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

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]

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

【问题讨论】:

  • 只需构造一个新列表,必要时变回原始列表。

标签: python list nested-lists


【解决方案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 或更高版本,则可以使用 mean(x)(来自包 statistics)而不是 lambda x: sum(x)/len(x)

【讨论】:

  • 谢谢,第 2 号有一个小错字:i
  • 避免使用lambda,只使用statistics库中stdlib中的内置mean
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-05
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多