python 中是否有 "map until" 或 "map while" 结构?

Is there a "map until" or "map while" construct in python?

我使用以下代码:

 for item1 in list1:
    for item2 in list2:
        if item2.add_item_if_belongs(item1):
            break

如果我没有 break 语句,我会将上面的语句替换为:

for item1 in list1:
    map(lambda item2: item2.add_item_if_belongs(item1), list2)

有什么方法可以 "map until" 或 "map while" 吗?

类似于:

from itertools import dropwhile, islice

for item1 in list1:
    map(lambda item2: item2.add_item(item1), 
        islice(dropwhile(lambda item2: item2.does_not_belong(item1),
               list2), 1))

因此,丢弃所有不属于的项目,然后只拿走第一个属于的项目。当然,这使得 map 毫无意义,因为它只对单个项目进行操作,而您忽略它创建的单个项目列表。

不用说原来的for循环更清晰了。

您显然并不需要 map 的输出,因此您需要的更多是 "apply" 类函数。您可以将最内层的循环移动到它自己的函数中。

def apply_until( fun, vals ):
    for val in vals:
        if fun(val):
            break

不过,您不应该为了更短的代码而放弃清晰度,IMO,for 循环非常清晰而且速度也很快。