[英]Keep consecutive number in list if the difference greater than a certain value
I would like to keep consecutive values in a list with difference >= than X Let's say I have this list:我想将连续值保留在一个列表中,其差异 >= 比 X 假设我有这个列表:
list = [1, 50, 70, 75, 100, 110]
and I would like to keep consecutive number numbers whose difference is >= 20:我想保留连续的数字,其差值 >= 20:
A = [1, 50, 70, 100]
To do this I'm using now this code:为此,我现在使用以下代码:
distance = 20
A = []
for i in (list):
if not A or (i - A[-1]) >= distance:
A.append(i)
There is any other way to do this with itertools or more-itertools?还有其他方法可以用 itertools 或 more-itertools 做到这一点吗? Thank you!
谢谢!
Try:尝试:
>>> arr = np.array([1, 50, 70, 75, 100, 110])
>>> mask = np.diff(arr) >= 20
>>> mask = np.insert(mask, 0, True)
>>> arr[mask]
array([ 1, 50, 70, 100])
For list l
, we could do -对于列表
l
,我们可以这样做 -
[l[0]]+[l[i] for i in range(1,len(l)) if l[i]-l[i-1]>=20]
For array a
, it would be -对于数组
a
,它将是 -
a[np.r_[True,np.diff(a)>=20]]
If you want to consider differences as absolute ones -如果您想将差异视为绝对差异 -
a[np.r_[True,np.abs(np.diff(a))>=20]
With simple generator function:使用简单的发电机function:
def filter_diff(lst):
v = lst[0]
yield v
for n in range(1, len(lst)):
if lst[n] - v >= 20:
v = lst[n]
yield v
lst = [1, 50, 70, 75, 100, 110]
print(list(filter_diff(lst))) # [1, 50, 70, 100]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.