鉴于
x = [5, 30, 58, 72]
y = [8, 35, 53, 60, 66, 67, 68, 73]
目标是遍历x_i
并找到大于y
但不大于x_i
x_i+1
的值
假设两个列表都已排序且所有项目都是唯一的,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
或其他内容实现相同的目标吗?
答案 0 :(得分:3)
您可以将numpy.searchsorted
与side='right'
一起使用,找出y
中第一个值大于x
的索引,然后使用索引提取元素;假定的y
中总有一个值比x
中的任何元素都大的简单版本可能是:
x = np.array([5, 30, 58, 72])
y = np.array([8, 35, 53, 60, 66, 67, 68, 73])
np.column_stack((x, y[np.searchsorted(y, x, side='right')]))
#array([[ 5, 8],
# [30, 35],
# [58, 60],
# [72, 73]])
给定y
已排序:
np.searchsorted(y, x, side='right')
# array([0, 1, 3, 7])
返回y
中第一个值的索引,该索引大于x
中的对应值。
答案 1 :(得分:2)
我们可以在pd.DataFrame
列表中使用merge_asof
direction = forward
,即
new = pd.merge_asof(pd.DataFrame(x,index=x), pd.DataFrame(y,index=y),on=0,left_index=True,direction='forward')
out = list(zip(new[0],new.index))
如果您不需要完全匹配,则需要将allow_exact_matches=False
传递给merge_asof
输出:
[(5, 8), (30, 35), (58, 60), (72, 73)]
答案 2 :(得分:1)
你可以通过迭代x
自己压缩来构造一个新的列表 - 偏移1个索引并附加y
的最后一个元素 - 然后迭代y,检查条件每次通过并打破最内层的循环。
out = []
for x_low, x_high in zip(x, x[1:]+y[-1:]):
for yy in y:
if (yy>x_low) and (yy<=x_high):
out.append((x_low,yy))
break
out
# returns:
[(5, 8), (30, 35), (58, 60), (72, 73)]
答案 3 :(得分:0)
def find(list1,list2):
final = []
for i in range(len(list1)):
pos=0
try:
while True:
if i+1==len(list1) and list1[i]<list2[pos]:
final.append((list1[i],list2[pos]))
raise Exception
if list1[i]<list2[pos] and list1[i+1]>list2[pos]:
final.append((list1[i],list2[pos]))
raise Exception
pos+=1
except: pass
return final