python前n项和存为一个数组_如何减去每一个n项每隔N-1项数组(Python)的?

I've looked into the many posts about getting every nth item of an array, and I used the method for slicing even and odd indices. However, I end up with an empty array for the final object. Any suggestions?

floc1 is an array, and I want to subtract every odd element from every even element:

period = abs(floc1[0::2] - floc1[1::2])

This currently gives me an empty array.

EDIT:

I've tried everything suggested in the comments below. The only thing that generated a different error was:

period = [i-j for i, j in zip(floc1[0::2], floc1[1::2])]

This gives:

Phi12 = ((tau)/(period))

ValueError: operands could not be broadcast together with shapes (1,8208) (0,)

In reference to:

Phi12 = ((tau)/(period))

Again, floc1 is definitely not an empty array. I saved it to a text file to confirm.

解决方案

Your example gives an error if floc1 is a list (which people often call an "array"). For a list you can do it this way.

>>> floc1 = [11, 5, 6, 2]

>>> it = iter(floc1)

>>> [x - next(it) for x in it]

[6, 4]

You can also use zip if you prefer see @wenzul's answer

If floc1 is a numpy.array - what you have already works

>>> import numpy as np

>>> floc1 = np.array([11, 5, 6, 2])

>>> abs(floc1[0::2] - floc1[1::2])

array([6, 4])

Perhaps your floc1 is actually an empty array

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值