假設串列如下:
list_of_strings = ['foo', 'bar', 'soap', 'sseo', 'spaseo', 'oess']
和一個子字串
to_find = 'seos'
我想在其中找到字串list_of_strings:
- 具有相同的長度
to_find - 具有相同的字符
to_find(與字符順序無關)
的輸出list_of_strings應該是'sseo', 'oess'](因為它包含來自to_find& 的所有字母的長度均為 4)
我有:
import itertools
list_of_strings = [string for string in list_of_strings if len(string) == len(to_find)]
result = [string for string in list_of_strings if any("".join(perm) in string for perm in itertools.permutations(to_find))]
找出運行我所做的代碼需要多長時間
import timeit
timeit.timeit("[string for string in list_of_strings if any(''.join(perm) in string for perm in itertools.permutations(to_find))]",
setup='from __main__ import list_of_strings, to_find', number=100000)
該程序需要一段時間才能給出輸出。我猜這是因為使用itertools.permutations.
有沒有辦法讓這段代碼更有效率?
謝謝
uj5u.com熱心網友回復:
如果順序無關緊要,您可以對字串進行排序并比較結果串列:
list_of_strings = ['foo', 'bar', 'soap', 'sseo', 'spaseo', 'oess']
to_find = sorted('seos')
matches = [word for word in list_of_strings if sorted(word) == to_find]
uj5u.com熱心網友回復:
這應該有效,因為Counter創建了一個類似 dict 的方法來計算每個字串中的字符數,目的是匹配字母及其計數,而不管它們的順序如何。
from collections import Counter
to_find_counter = Counter(to_find)
# go through the list and check if the Counter is the same as the Counter of to_find
[x for x in list_of_strings if Counter(x)==to_find_counter]
['sseo', 'oess']
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/477280.html
下一篇:如何在C#中更改字串的值?
