【发布时间】:2018-04-13 08:11:47
【问题描述】:
给定
x = [5, 30, 58, 72]
y = [8, 35, 53, 60, 66, 67, 68, 73]
目标是遍历x_i 并找到大于x_i 但不大于x_i+1 的y 值
假设两个列表都已排序并且所有项目都是唯一的,那么在给定 x 和 y 的情况下所需的输出是:
[(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 或其他方式实现相同的目标?
【问题讨论】:
-
当
y中有多个位于x[i]和x[i+1]之间的号码时,您希望发生什么? -
抢先。
标签: python list pandas numpy range