Si j'ai un collection of strings
est-il une structure de données ou une fonction qui pourrait améliorer la vitesse de vérification si l'un des éléments des collections sont substrings
sur ma chaîne principale ?Python3 rapide pour trouver si des éléments dans les collections sont sous-chaîne de chaîne
En ce moment je suis en boucle à travers mon tableau de chaînes et en utilisant l'opérateur in
. Y at-il un moyen plus rapide?
import timing
## string match in first do_not_scan
## 0:00:00.029332
## string not in do_not_scan
## 0:00:00.035179
def check_if_substring():
for x in do_not_scan:
if x in string:
return True
return False
## string match in first do_not_scan
## 0:00:00.046530
## string not in do_not_scan
## 0:00:00.067439
def index_of():
for x in do_not_scan:
try:
string.index(x)
return True
except:
return False
## string match in first do_not_scan
## 0:00:00.047654
## string not in do_not_scan
## 0:00:00.070596
def find_def():
for x in do_not_scan:
if string.find(x) != -1:
return True
return False
string = '/usr/documents/apps/components/login'
do_not_scan = ['node_modules','bower_components']
for x in range(100000):
find_def()
index_of()
check_if_substring()
Est-il possible que vous ayez collé quelque chose de mal ici?Ou est 'string = 'a'' juste un échantillon. Parce que 'node_modules' ne sera jamais dans' string'. Cela dit, pouvez-vous utiliser une carte. Où les clés sont les éléments de 'do_not_scan'. Alors la recherche est O (1) – Cripto
juste un échantillon pour démontrer 'string' ne peut contenir aucun élément de' do_not_scan'. Je n'ai jamais utilisé de carte avant comment vous y prendrez-vous? – ClickThisNick
Voulez-vous l'analogue de 'grep -l -Ff collections_of_strings main_string'? où le fichier 'collections_of_strings' contient des collections de chaînes (une par ligne) et le fichier' main_string' contient la chaîne principale (telle quelle). – jfs