列表中的数字,查找周围环境的平均值 [英] numbers in a list, find average of surroundings

查看:72
本文介绍了列表中的数字,查找周围环境的平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:

给出一个数字列表listA,编写一个程序来生成一个新列表listB,该列表具有与listA相同的元素数,这样新列表中的每个元素都是其邻居及其自身的平均值在原始列表中.

Given a list listA of numbers, write a program that generates a new list listB with the same number of elements as listA, such that each element in the new list is the average of its neighbors and itself in the original list.

例如,如果listA = [5, 1, 3, 8, 4]listB = [3.0, 3.0, 4.0, 5.0, 6.0],其中:

(5 + 1)/2 = 3.0 
(5 + 1 + 3)/3 = 3.0 
(1 + 3 + 8)/3 = 4.0 
(3 + 8 + 4)/3 = 5.0 
(8 + 4)/2 = 6.0 

所以我可以得到第一部分,最后一部分,因为它们只处理2个数字,但是对于中间部分,我无法得到它.我的循环是错误的,但我不完全知道.这是我到目前为止所拥有的.

so i can get the first part, and the last part since they only deal with 2 numbers, but for the middle part i can not get it. my loop is wrong, but i dont know exactly. this is what i have so far.

listA= [5,1,3,8,4]

N=len(listA)
print(listA)

listB=[]
listB.append((listA[0]+listA[1])/2)

y=0
x=1
while x in listA:
    y=((listA[x-1] + list[x] + list[x+1])/3)
    listB.append(y)
y=y+1

listB.append((listA[-1]+listA[-2])/2)

print(listB)

推荐答案

您可以使用迭代器来执行此操作,而不必求助于遍历索引:

You can do this using iterators without having to resort to looping through indices:

import itertools

def neighbours(items, fill=None):
    before = itertools.chain([fill], items)
    after = itertools.chain(items, [fill]) #You could use itertools.zip_longest() later instead.
    next(after)
    for a, b, c in zip(before, items, after):
        yield [value for value in (a, b, c) if value is not fill]

使用方式如下:

>>> items = [5, 1, 3, 8, 4]
>>> [sum(values)/len(values) for values in neighbours(items)]
[3.0, 3.0, 4.0, 5.0, 6.0]

那么这是如何工作的?我们创建一些额外的迭代器-之前和之后的值.我们使用itertools.chain分别在开头和结尾处添加一个额外的值,以便允许我们在正确的时间获得正确的值(而不用完所有项).然后,我们将下一项向前推进,将其放在正确的位置,然后遍历,返回非None的值.这意味着我们可以以一种非常自然的方式循环浏览.

So how does this work? We create some extra iterators - for the before and after values. We use itertools.chain to add an extra value to the beginning and end respectively, in order to allow us to get the right values at the right time (and not run out of items). We then advance the later item on one, to put it in the right position, then loop through, returning the values that are not None. This means we can just loop through in a very natural way.

请注意,这需要一个列表,因为迭代器将被耗尽.如果您需要它在迭代器上懒惰地工作,下面的示例使用itertools.tee()来完成工作:

Note that this requires a list, as an iterator will be exhausted. If you need it to work lazily on an iterator, the following example uses itertools.tee() to do the job:

def neighbours(items, fill=None):
    b, i, a = itertools.tee(items, 3)
    before = itertools.chain([fill], b)
    after = itertools.chain(a, [fill])
    next(a)
    for a, b, c in zip(before, i, after):
        yield [value for value in (a, b, c) if value is not fill]

这篇关于列表中的数字,查找周围环境的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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