1 回答

TA貢獻1817條經(jīng)驗 獲得超6個贊
itertools.product返回一個迭代器,迭代器一般都是“single-pass”的(可能有例外)。一旦一個元素被迭代,它就不會被再次迭代。
但是,您可以itertools.product在兩個地方使用結果,一次作為 for 的參數(shù),一次作為 for 的starmap參數(shù)compress。因此,如果starmap“彈出”一個元素,product那么下一次compress“彈出”來自同一產(chǎn)品的元素,它將接收下一個元素(不是同一個元素)。
在大多數(shù)情況下,我建議不要將此類迭代器分配為變量,正是因為它們的“單程”性質。
所以一個明顯的解決方法是兩次生成產(chǎn)品:
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')]
在這種情況下,我認為生成器函數(shù)中的循環(huán)比使用 multiple 更具可讀性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')]
添加回答
舉報