Python: lambda: 找到 2 个排序的无限迭代器的第一个公共元素

Python: lambda: find the first common element of 2 sorted infinite iterators

我正在尝试获得一个 1 线性 lambda,它将 return 2 个排序迭代器的第一个公共元素。

在这里,我使用 NON FINITE 迭代器(比如 count() 会永远迭代),你不能将其转换回列表或集合。 (set(count(5)) 只会让你的 python 崩溃)。

例如:

from itertools import count
x = count(7)
y = count(5)

结果为 7。

您可以按如下方式使用交集:

elt = min(set(x).intersection(set(y)))

遍历列表直到找到一个共同的对象。否则发现将是None。使用迭代器已排序且不需要额外内存的事实。

idx_x = 0
idx_y = 0
found = None
while idx_x < len(x) and idx_y < len(y):
    if x[idx_x] == y[idx_y]:
        found= x[idx_x]
        break
    if x[idx_x] < y[idx_y]:
        idx_x +=1
    else:
        idx_y += 1

试试这个:

first = lambda x, y: next((a for a in x if a in set(y)), None)

演示:

>>> x = xrange(5, 10)
>>> y = xrange(7, 11)
>>> first = lambda x, y: next((a for a in x if a in set(y)), None)
>>> first(x, y)
7

给你:

next(x for x in count(7) for y in count(5) if x==y)