我有两个列表:
a = [1,3,6,10,20]
b = [2,4,9,12,15,22,24,25]
现在,我想创建一个新列表,其中包含前两个列表中的对。这些对的定义如下:
a[i]
b
存在,则a[i]
和a[i+1]
之间a[i+1]
中的最高数字,否则仅大于a[i]
,如果存在a[i]
,则仅比a[-1]
大0 < i < max(len(a),len(b))
结果如下:
pair = [[1,2],[3,4],[6,9],[10,15],[20,25]]
有人知道该怎么做吗?
这是我到目前为止所做的:
a = [1,3,6,10,20]
b = [2,4,9,12,15,22,24,25]
pairs = []
counter = 0
for i in range(max(len(a),len(b))):
try:
# get a[i]
ai = a[i]
except:
ai = a[-1]
try:
# get a[i+1]
ai1 = a[i+1]
except:
ai1 = b[-1]+1
temp = []
for bi in b:
if ai < bi and bi < ai1:
temp.append(bi)
# Avoid adding the last element of b again and again until i = len(b)
if max(temp) == b[-1]:
counter = counter +1
if counter <= 1:
print(max(temp))
pairs.append([ai,max(temp)])
没关系,因为它可以完成工作,但是我想知道,是否有更好,更有效的方法?
答案 0 :(得分:1)
您可以进行二进制搜索,因为对数组进行了排序,所以不必搜索a[i] < b[j]
,而只需搜索a[i+1] > b[j]
(如果其中没有元素,则此代码将返回无效结果。 b
这样a[i] < b < a[b+1]
):
import bisect
def pairs(a, b):
for (a1, a2) in zip(a, a[1:]):
yield a1, b[bisect.bisect_left(b, a2) - 1]
yield a[-1], b[-1]
print(list(pairs([1,3,6,10,20], [2,4,9,12,15,22,24,25])))
[(1, 2), (3, 4), (6, 9), (10, 15), (20, 25)]
答案 1 :(得分:1)
这是另一种方法:
a = [1,3,6,10,20]
b = [2,4,9,12,15,22,24,25]
merged = sorted(a + b, reverse=True)
mask = [(False, True)[x in a] for x in merged]
flag = True
good = []
for m, n in zip(mask, merged):
if m is flag:
continue
else:
good.append(n)
flag = not flag
pairs = list(zip(good[1::2], good[::2]))[::-1]
pairs
>>> [(1, 2), (3, 4), (6, 9), (10, 15), (20, 25)]