列表列表中的平均列表 - 有没有更有效的方法? [英] Average List from a List of Lists - Is there a more efficient way?

查看:51
本文介绍了列表列表中的平均列表 - 有没有更有效的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为run"的列表.我正在使用我的代码的这一部分创建这些列表的平均值:

ave = [0 for t in range(s)]对于范围内的 t:z = 0对于范围(l)中的我:z = z + 运行[i][t]#将值转换为字符串以供输出# 将 \n 添加到输出ave[t]= ((str(z/l) + "\n"))

令我惊讶的是,这段代码在我第一次编写时就起作用了.我现在计划使用更大的列表和更多的值,性能问题可能会发挥作用.这种编写平均使用计算资源的方法是否效率低下,我该如何编写更高效的代码?

解决方案

列表推导式可能更高效.

<预><代码>>>>运行 = [[1, 2, 3, 4, 5], [6, 7, 8, 9], [10, 11, 12, 13]]>>>[sum(elem)/len(elem) for elem in zip(*run)][5.666666666666667, 6.666666666666667, 7.666666666666667, 8.666666666666666]

或者,您可以尝试 map()

<预><代码>>>>列表(地图(lambda x:总和(x)/len(x),zip(*运行)))[5.666666666666667, 6.666666666666667, 7.666666666666667, 8.666666666666666]

I have a list of lists named 'run'. I am creating an average of those lists using this section of my code:

ave = [0 for t in range(s)]
for t in range(s):
    z = 0
    for i in range(l):
        z = z + run[i][t]
        #Converted values to a string for output purposes
        # Added \n to output
        ave[t]= ((str(z / l) + "\n"))

Much to my surprise, this code worked the first time that I wrote it. I'm now planning on working with much larger lists and many more values, and it's possible that performance issues will come into play. Is this method of writing an average inefficient in its use of computational resources, and how could I write code that was more efficient?

解决方案

List comprehensions may be more efficient.

>>> run = [[1, 2, 3, 4, 5], [6, 7, 8, 9], [10, 11, 12, 13]]
>>> [sum(elem)/len(elem) for elem in zip(*run)]  
[5.666666666666667, 6.666666666666667, 7.666666666666667, 8.666666666666666]

Alternatively, you could try map()

>>> list(map(lambda x: sum(x)/len(x), zip(*run)))
[5.666666666666667, 6.666666666666667, 7.666666666666667, 8.666666666666666]

这篇关于列表列表中的平均列表 - 有没有更有效的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆