第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python 的 itertools.compress 不像布爾掩碼那樣工作。為什么?

Python 的 itertools.compress 不像布爾掩碼那樣工作。為什么?

瀟湘沐 2021-10-19 17:06:40
我有一個字符串列表,我想使用itertools.compress.我有大量的字符串需要對照句子列表進行檢查。因此,我想使用 itertools 來節(jié)省資源。無法按預期工作的部分是通過壓縮進行的布爾屏蔽。from itertools import product, starmap, compressdef is_in(string, other_string):    return string in other_stringto_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')]
查看完整描述

1 回答

?
慕的地6264312

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')]


查看完整回答
反對 回復 2021-10-19
  • 1 回答
  • 0 關注
  • 197 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號