gpt4 book ai didi

Python itertools.compress 的工作方式与 bool 掩码不同。为什么?

转载 作者:行者123 更新时间:2023-11-30 22:00:16 25 4
gpt4 key购买 nike

我有一个字符串列表,我想使用 itertools.compress 给定 bool 值掩码来过滤这些字符串。

我有大量字符串需要对照句子列表进行检查。因此,我想使用itertools来节省资源。未按预期工作的部分是通过压缩进行的 bool 掩码。

from itertools import product, starmap, compress

def is_in(string, other_string):
return string in other_string

to_find = ['hello', 'bye']
some_sentences = ['hello to you', ' hello and bye', 'bye bye']

cartesian = product(to_find, some_sentences)
matched_mask = starmap(is_in, cartesian)
matched = compress(cartesian, matched_mask)
print(list(matched))
actual_result = [('hello', 'hello to you'), ('bye', ' hello and bye')]

expected = [('hello', 'hello to you'),
('hello', 'hello and bye'),
('bye', ' hello and bye'),
('bye', 'bye bye')]

最佳答案

itertools.product返回一个迭代器,迭代器通常是“单遍”(可能有异常(exception))。一旦一个元素被迭代,它就不会被再次迭代。

但是,您可以在两个地方使用 itertools.product 的结果,一次作为 starmap 的参数,一次作为 compress 的参数。因此,如果starmapproduct“弹出”一个元素,那么下次compress从同一产品“弹出”一个元素时,它将收到下一个元素(不是同一元素)。

在大多数情况下,我建议不要将此类迭代器分配为变量,正是因为它们的“单遍”性质。

因此,一个明显的解决方法是生成两次产品:

matched_mask = starmap(is_in, product(to_find, some_sentences))
matched = compress(product(to_find, some_sentences), matched_mask)
print(list(matched))
# [('hello', 'hello to you'), ('hello', ' hello and bye'), ('bye', ' hello and bye'), ('bye', 'bye bye')]

在这种情况下,我认为生成器函数中的循环比使用多个 itertools 更具可读性:

from itertools import product

def func(to_find, some_sentences):
for sub, sentence in product(to_find, some_sentences):
if sub in sentence:
yield sub, sentence

然后像这样使用它:

>>> to_find = ['hello','bye']
>>> some_sentences = ['hello to you', ' hello and bye', 'bye bye']
>>> list(func(to_find, some_sentences))
[('hello', 'hello to you'),
('hello', ' hello and bye'),
('bye', ' hello and bye'),
('bye', 'bye bye')]

或者如果您喜欢俏皮话:

>>> [(sub, sentence) for sub, sentence in product(to_find, some_sentences) if sub in sentence]
[('hello', 'hello to you'),
('hello', ' hello and bye'),
('bye', ' hello and bye'),
('bye', 'bye bye')]

关于Python itertools.compress 的工作方式与 bool 掩码不同。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54352343/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com