列表的平均值,以100个项目为块 [英] The average value of a list, in chunks of 100 items

查看:186
本文介绍了列表的平均值,以100个项目为块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文件,其中有1084个元素.我列出了他们.

I have a text file in which I have, for example, 1084 elements. I list them.

import csv
a = []
with open('example.txt', 'r') as csvfile:
    file_name = csv.reader(csvfile, delimiter='\t')
    for row in file_name:
        a.append(int(row[1]))
print(a)

[144, 67, 5, 23, 64...456, 78, 124]

接下来,我需要取列表中每100个元素的平均值,取最后84个元素的平均值,并将其带到新列表中. 我到底该怎么做?也许是numpy的?

Next, I need to take the average of every one hundred elements of the list, average the last 84 elements and bring it to a new list. How exactly can I do this? Maybe with numpy?

推荐答案

这将在Python 3中起作用,因为您将print编写为函数,所以我假设您正在使用Python 3.在Python 2中,您需要确保该除法是浮点除法.

This will work in Python 3, which I'm going to assume you're using since you wrote print as a function. In Python 2 you'll need to make sure that the division is floating point division.

# a = [...]

# Separate the groups. The last slice will be fine with less than 100 numbers.
groups = [a[x:x+100] for x in range(0, len(a), 100)]

# Simple math to calculate the means
means = [sum(group)/len(group) for group in groups]

如果您确实想在Python 2中执行此操作,则可以在最后一行中将len(group)替换为float(len(group)),以强制进行浮点除法;或者,您可以在顶部添加from __future__ import division /a>,尽管这样做会更改整个模块,而不仅仅是这一行.

If you do want to do this in Python 2, you can replace len(group) in the last line with float(len(group)), so that it forces floating point division; or, you can add from __future__ import division at the top of your module, although doing that will change it for the whole module, not just this line.

这是一个很好的,可重复使用的版本,可与迭代器一起使用,它本身就是生成器:

Here's a nice, reusable version that works with iterators, and is itself a generator:

from itertools import islice

def means_of_slices(iterable, slice_size):
    iterator = iter(iterable)
    while True:
        slice = list(islice(iterator, slice_size))
        if slice:
            yield sum(slice)/len(slice)
        else:
            return

a = [1, 2, 3, 4, 5, 6]

means = list(means_of_slices(a, 2))

print(means)
# [1.5, 3.5, 5.5]

您不应使代码的通用性超出实际需求,但为了获得额外的经验值,您可以使代码更加通用和可组合.上面的内容足以供您使用.

You shouldn't make code too much more general than you actually need it, but for bonus experience points, you can make this even more general and composable. The above should be more than enough for your use though.

这篇关于列表的平均值,以100个项目为块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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