I am trying to fumble through python, and learn the best way to do things. I have a string where I am doing a compare with another string to see if there is a match:
if paid[j].find(d)>=0:
#BLAH BLAH
If d
were an list, what is the most efficient way to see if the string contained in paid[j] has a match to any value in d
?
This question is related to
python
I assume you mean list
and not array
? There is such a thing as an array in Python, but more often than not you want a list instead of an array.
The way to check if a list contains a value is to use in
:
if paid[j] in d:
# ...
In Python you may use the in
operator. You can do stuff like this:
>>> "c" in "abc"
True
Taking this further, you can check for complex structures, like tuples:
>>> (2, 4, 8) in ((1, 2, 3), (2, 4, 8))
True
for word in d:
if d in paid[j]:
do_something()
will try all the words in the list d
and check if they can be found in the string paid[j]
.
This is not very efficient since paid[j]
has to be scanned again for each word in d
. You could also use two sets, one composed of the words in the sentence, one of your list, and then look at the intersection of the sets.
sentence = "words don't come easy"
d = ["come", "together", "easy", "does", "it"]
s1 = set(sentence.split())
s2 = set(d)
print (s1.intersection(s2))
Output:
{'come', 'easy'}
Source: Stackoverflow.com