假設串列如下:
list_of_strings = ['foo', 'bar', 'soap', 'seo', 'paseo', 'oes']
和一個子字串
to_find = 'eos'
我想找到list_of_strings與子字串匹配的字串。的輸出list_of_strings應該是['seo', 'paseo', 'oes'](因為它在to_find子字串中包含所有字母)
我嘗試了幾件事:
a = next((string for string in list_of_strings if to_find in string), None) # gives NoneType object as output
&
result = [string for string in list_of_strings if to_find in string] # gives [] as output
但兩個代碼都不起作用。
有人可以告訴我我在做什么錯嗎?
謝謝
uj5u.com熱心網友回復:
從邏輯上講,您的問題是將單詞中的字符集與串列中每個單詞中的字符集進行比較。如果后一個單詞包含要查找的單詞中的所有字符,則它是匹配的。這是使用串列推導和 set 的一種方法intesection:
list_of_strings = ['foo', 'bar', 'soap', 'seo', 'paseo', 'oes']
to_find = 'eos'
to_find_set = set(list(to_find))
output = [x for x in list_of_strings if len(to_find_set.intersection(set(list(x)))) == len(to_find_set)]
print(output) # ['seo', 'paseo', 'oes']
如果您想為任何不匹配的輸入字串保留一個空字串占位符,請使用此版本:
output = [x if len(to_find_set.intersection(set(list(x)))) == len(to_find_set) else '' for x in list_of_strings]
print(output) # ['', '', '', 'seo', 'paseo', 'oes']
uj5u.com熱心網友回復:
您是否需要 to_find 的字母彼此相鄰,或者所有字母都應該在單詞中?基本上:seabco匹配與否?
[你的問題不包括這個細節,你經常使用“子字串”,但也“因為它在 to_find 中有所有字母”,所以我不知道如何解釋它。]
如果seabco匹配,那么@Tim Biegeleisen 的答案是正確的。如果字母需要彼此相鄰(但當然可以任意順序),請查看以下內容:
如果to_find相對較短,您可以只生成字母的所有排列(n!其中,這里 (3!) = 6: eos, eso, oes, ose, seo, soe)并檢查in。
import itertools
list_of_strings = ['foo', 'bar', 'soap', 'seo', 'paseo', 'oes']
to_find = 'eos'
result = [string for string in list_of_strings if any("".join(perm) in string for perm in itertools.permutations(to_find))]
https://docs.python.org/3/library/itertools.html#itertools.permutations
我們這樣做"".join(perm)是因為 perm 是一個元組,我們需要一個字串。
>>> result = [string for string in list_of_strings if any("".join(perm) in string for perm in itertools.permutations(to_find))]
>>> result
['seo', 'paseo', 'oes']
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/476246.html
上一篇:這是.NET中StackExchange.Redis中流水線的正確實作嗎?
下一篇:根據字串有條件地拆分列
