[英]Put average of nested list values into new list
I have the following list:我有以下清单:
x = [(27.3703703703704, 2.5679012345679, 5.67901234567901,
6.97530864197531, 1.90123456790123, 0.740740740740741,
0.440136054421769, 0.867718446601942),
(25.2608695652174, 1.73913043478261, 6.07246376811594,
7.3768115942029, 1.57971014492754, 0.710144927536232,
0.4875, 0.710227272727273)]
I'm looking for a way to get the average of each of the lists nested within the main list, and create a new list of the averages.我正在寻找一种方法来获取嵌套在主列表中的每个列表的平均值,并创建一个新的平均值列表。 So in the case of the above list, the output would be something like:因此,在上述列表的情况下,输出将类似于:
[[26.315],[2.145],[5.87],etc...]
I would like to apply this formula regardless of the amount of lists nested within the main list.无论嵌套在主列表中的列表数量如何,我都想应用此公式。
I assume your list of tuples of one-element lists is looking for the sum of each unpacked element inside the tuple, and a list of those options.我假设您的单元素列表的元组列表正在寻找元组中每个未打包元素的总和,以及这些选项的列表。 If that's not what you're looking for, this won't work.如果这不是你要找的东西,这将不起作用。
result = [sum([sublst[0] for sublst in tup])/len(tup) for tup in x]
result = [sum(tup)/len(tup) for tup in x]
result = [[sum(tup)/len(tup)] for tup in x]
An easy way to acheive this is:实现这一目标的简单方法是:
means = [] # Defines a new empty list
for sublist in x: # iterates over the tuples in your list
means.append([sum(sublist)/len(sublist)]) # Put the mean of the sublist in the means list
This will work no matter how many sublists are in your list.无论您的列表中有多少个子列表,这都将起作用。 I would advise you read a bit on list comprehensions: https://docs.python.org/2/tutorial/datastructures.html我建议您阅读一些关于列表理解的内容: https : //docs.python.org/2/tutorial/datastructures.html
It looks like you're looking for the zip
function:看起来您正在寻找zip
功能:
[sum(l)/len(l) for l in zip(*x)]
zip
combines a collection of tuples or lists pairwise, which looks like what you want for your averages. zip
成对组合了一组元组或列表,这看起来像您想要的平均值。 then you just use sum()/len()
to compute the average of each pair.然后您只需使用sum()/len()
来计算每对的平均值。
*x
notation means pass the list as though it were individual arguments, ie as if you called: zip(x[0], x[1], ..., x[len(x)-1])
*x
表示法意味着传递列表,就好像它是单独的参数一样,即就像您调用: zip(x[0], x[1], ..., x[len(x)-1])
r = [[sum(i)/len(i)] for i in x]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.