For approaches to retrieving partial matches in a numeric list, go to:
But if you’re looking for how to retrieve partial matches for a list of strings, you’ll find the best approaches concisely explained in the answer below.
SO: Python list lookup with partial match shows how to return a bool
, if a list
contains an element that partially matches (e.g. begins
, ends
, or contains
) a certain string. But how can you return the element itself, instead of True
or False
Example:
JavaScript
x
3
1
l = ['ones', 'twos', 'threes']
2
wanted = 'three'
3
Here, the approach in the linked question will return True
using:
JavaScript
1
2
1
any(s.startswith(wanted) for s in l)
2
So how can you return the element 'threes'
instead?
Advertisement
Answer
startswith
andin
, return a Boolean.- The
in
operator is a test of membership. - This can be performed with a
list-comprehension
orfilter
. - Using a
list-comprehension
, within
, is the fastest implementation tested. - If case is not an issue, consider mapping all the words to lowercase.
l = list(map(str.lower, l))
.
- Tested with python 3.11.0
filter
:
- Using
filter
creates afilter
object, solist()
is used to show all the matching values in alist
.
JavaScript
1
13
13
1
l = ['ones', 'twos', 'threes']
2
wanted = 'three'
3
4
# using startswith
5
result = list(filter(lambda x: x.startswith(wanted), l))
6
7
# using in
8
result = list(filter(lambda x: wanted in x, l))
9
10
print(result)
11
[out]:
12
['threes']
13
list-comprehension
JavaScript
1
13
13
1
l = ['ones', 'twos', 'threes']
2
wanted = 'three'
3
4
# using startswith
5
result = [v for v in l if v.startswith(wanted)]
6
7
# using in
8
result = [v for v in l if wanted in v]
9
10
print(result)
11
[out]:
12
['threes']
13
Which implementation is faster?
- Tested in Jupyter Lab using the
words
corpus fromnltk v3.7
, which has 236736 words - Words with
'three'
['three', 'threefold', 'threefolded', 'threefoldedness', 'threefoldly', 'threefoldness', 'threeling', 'threeness', 'threepence', 'threepenny', 'threepennyworth', 'threescore', 'threesome']
JavaScript
1
7
1
from nltk.corpus import words
2
3
%timeit list(filter(lambda x: x.startswith(wanted), words.words()))
4
%timeit list(filter(lambda x: wanted in x, words.words()))
5
%timeit [v for v in words.words() if v.startswith(wanted)]
6
%timeit [v for v in words.words() if wanted in v]
7
%timeit
results
JavaScript
1
5
1
62.8 ms ± 816 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
2
53.8 ms ± 982 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
3
56.9 ms ± 1.33 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
4
47.5 ms ± 1.04 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
5