[英]Pairs of numbers from two lists
我有两个清单:
a = [1,3,6,10,20]
b = [2,4,9,12,15,22,24,25]
现在,我想创建一个新列表,其中包含前两个列表中的对。 对被定义如下:
a[i]
a[i+1]
存在,则a[i]
和a[i+1]
之间a[i]
b
的最大数字,否则只有大于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)])
没关系,因为它完成了工作,但我想知道,如果有更好,更有效的方法吗?
您可以进行二分查找,因为数组已排序,您不必搜索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)]
这是另一种方法:
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)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.