Given
x = [5, 30, 58, 72]
y = [8, 35, 53, 60, 66, 67, 68, 73]
目标是迭代x_i
并找到值y
那大于x_i
但不大于x_i+1
假设两个列表都已排序并且所有项目都是唯一的,给定所需的输出x
and y
is:
[(5, 8), (30, 35), (58, 60), (72, 73)]
我试过了:
def per_window(sequence, n=1):
"""
From http://stackoverflow.com/q/42220614/610569
>>> list(per_window([1,2,3,4], n=2))
[(1, 2), (2, 3), (3, 4)]
>>> list(per_window([1,2,3,4], n=3))
[(1, 2, 3), (2, 3, 4)]
"""
start, stop = 0, n
seq = list(sequence)
while stop <= len(seq):
yield tuple(seq[start:stop])
start += 1
stop += 1
x = [5, 30, 58, 72]
y = [8, 35, 53, 60, 66, 67, 68, 73]
r = []
for xi, xiplus1 in per_window(x, 2):
for j, yj in enumerate(y):
if yj > xi and yj < xiplus1:
r.append((xi, yj))
break
# For the last x value.
# For the last x value.
for j, yj in enumerate(y):
if yj > xiplus1:
r.append((xiplus1, yj))
break
但是有没有一种更简单的方法可以达到相同的效果numpy
, pandas
或者是其他东西?