如何将多个列表压缩到字典中并找到它们的平均值
How do I zip multiple lists inside a dictionary and find mean of them
我如何将列表压缩到字典中:
somedict = {a: [1,2,3, b: [4,5,6], c: [7,8,9], d: [10,11,12]}
我想将列表中的所有值压缩成这样:
dlist = [[1,4,7,10], [2,5,8,11], [3,6,9,12]]
然后添加它们,使其变为:
sumlist = [21, 26, 30]
然后在最后除以每个列表的长度求和:
meanlist = [5.25, 6.5, 7.5]
我在想也许可以将列表存储在一个 numpy 数组中并调用 np.mean。
这是一个不使用 numpy 的解决方案
首先我们声明字典
somedict = {"a": [1, 2, 3], "b": [4, 5, 6], "c": [7, 8, 9], "d": [10, 11, 12]}
然后我们将字典中的每个键压缩到列表列表
dlist = list(zip(somedict["a"], somedict["b"], somedict["c"], somedict["d"]))
然后我们将总和映射到每个子列表以创建总和列表
sumlist = list(map(sum, dlist))
我在这里使用 lambda 函数创建一个未命名的函数,该函数计算列表的平均值并将其映射到每个子列表。
meanlist = list(map(lambda x: sum(x)/len(x), dlist))
print("dlist: {}".format(list(dlist)))
print("Sumlist: {}".format(sumlist))
print("meanList: {}".format(meanlist))
#Output:
#dlist: [(1, 4, 7, 10), (2, 5, 8, 11), (3, 6, 9, 12)]
#Sumlist: [22, 26, 30]
#meanList: [5.5, 6.5, 7.5]
我如何将列表压缩到字典中:
somedict = {a: [1,2,3, b: [4,5,6], c: [7,8,9], d: [10,11,12]}
我想将列表中的所有值压缩成这样:
dlist = [[1,4,7,10], [2,5,8,11], [3,6,9,12]]
然后添加它们,使其变为:
sumlist = [21, 26, 30]
然后在最后除以每个列表的长度求和:
meanlist = [5.25, 6.5, 7.5]
我在想也许可以将列表存储在一个 numpy 数组中并调用 np.mean。
这是一个不使用 numpy 的解决方案
首先我们声明字典
somedict = {"a": [1, 2, 3], "b": [4, 5, 6], "c": [7, 8, 9], "d": [10, 11, 12]}
然后我们将字典中的每个键压缩到列表列表
dlist = list(zip(somedict["a"], somedict["b"], somedict["c"], somedict["d"]))
然后我们将总和映射到每个子列表以创建总和列表
sumlist = list(map(sum, dlist))
我在这里使用 lambda 函数创建一个未命名的函数,该函数计算列表的平均值并将其映射到每个子列表。
meanlist = list(map(lambda x: sum(x)/len(x), dlist))
print("dlist: {}".format(list(dlist)))
print("Sumlist: {}".format(sumlist))
print("meanList: {}".format(meanlist))
#Output:
#dlist: [(1, 4, 7, 10), (2, 5, 8, 11), (3, 6, 9, 12)]
#Sumlist: [22, 26, 30]
#meanList: [5.5, 6.5, 7.5]