简体   繁体   English

总结邻居数

[英]Summing up neighbors numbers

I am trying to iterate over all numbers in my list and I want to sum each number with his neighbor.我正在尝试遍历列表中的所有数字,并且我想将每个数字与他的邻居相加。

    DataList=[2,7,18,22]
    total=0
    for number in DataList:
        total+=number
    print(DataList[0] + DataList[1])
    print(DataList[0] + DataList[1]+DataList[2])
    print(DataList[1] + DataList[2]+DataList[3])
    print(DataList[2] + DataList[3])

#Output from code above
9
27
47
40

As you can see from code above I already made some solution but this solution is not good (in realistic I have very big sample) because I typed all commands with print, so can anybody help me how to solve this problem and make automatic loop and make sum over all neighbors numbers?正如您从上面的代码中看到的那样,我已经提出了一些解决方案,但是这个解决方案并不好(实际上我有非常大的示例)因为我用 print 输入了所有命令,所以任何人都可以帮助我如何解决这个问题并进行自动循环和对所有邻居数求和?

Simply use a mix of if-elif-else with loop as:只需将if-elif-else与循环混合使用:

DataList=[2,7,18,22]
for i in range(len(DataList)):
    if i == 0:
        print(DataList[i] + DataList[i+1])
    elif i == len(DataList)-1:
        print(DataList[i-1] + DataList[i])
    else:
        print(DataList[i-1] + DataList[i] + DataList[i+1])

There is a function in itertools which is accumulate it is actually functioning as you want. itertools 中有一个 function ,它是累积的,它实际上可以按照您的意愿运行。 This is the python docs you can find accumulate here https://docs.python.org/3/library/itertools.html这是 python 文档,您可以在这里找到累积的https://docs.python.org/3/library/itertools.ZA7635FDC70D2EFC26

DataList=[2,7,18,22]
xp=[items for item in [[sum(DataList[:x+1]),sum(DataList[x:])]for x in range(len(DataList))] for items in item]
print(xp)

I think this is what you intend to have:我认为这是您打算拥有的:

totalNum = len(DataList)
totalSum = 0
sumArray = [0]*totalNum

for i in range(totalNum):
    sumArray[i] += DataList[i]
    if i+1 < totalNum:
        sumArray[i] += DataList[i+1]
    if i-1 > 0:
        sumArray[i] += DataList[i-1]
for i in range(totalNum):
    print(sumArray[i])

A "clever" way to do it would be to create three versions of the list with 0 's appended, them sum them up.一种“聪明”的方法是创建三个版本的列表,并附加0 ,然后将它们相加。

DataList = [ 2, 7, 18, 22 ]

l = [ 0, 0 ] + DataList
c = [ 0 ] + DataList + [ 0 ]
r = DataList + [ 0, 0 ]

sums = [ sum( n ) for n in zip( l, c, r ) ]

You can then slice the elements off the ends if you don't want them.然后,如果您不想要它们,您可以将元素从末端切掉。

Using this approach you can also use numpy to speed of the calculation for large lists.使用这种方法,您还可以使用numpy来加快大型列表的计算速度。

sums = np.sum( np.array( [ l, c, r ] ), axis = 0 )

For different sized lists you can see the numpy payoff (note y-axis is in log scale)对于不同大小的列表,您可以看到numpy收益(注意 y 轴是对数刻度) 列表和 numpy 邻居和的时序比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM