Globbing in List Search?

Peter Otten __peter__ at web.de
Thu Mar 25 02:31:08 EST 2004


Ed Suominen wrote:

> k = x.index(filter(lambda x: x.startswith(term), x)[0])
> 
> where "term" acts like it has an implicit "*" at the end.
> 
> Any better ideas?
> 
> Ed Suominen wrote:
> 
>> Does Python have a globbing-type list search capability, like "lsearch
>> -glob $list" in TCL?

The glob module has a reference to fnmatch, which should meet your needs:

>>> names = ["axb", "asowhatb", "abc"]

Find all matches:

>>> fnmatch.filter(names, "a*b")
['axb', 'asowhatb']


Find all matching indices:

>>> [i for (i, n) in enumerate(names) if fnmatch.fnmatch(n, "a*b")]
[0, 1]

Find first matching index or -1:
 
>>> def index(names, pattern):
...     for i, n in enumerate(names):
...             if fnmatch.fnmatch(n, pattern):
...                     return i
...     return -1
...
>>> index(names, "a*b")
0
>>> index(names, "a*x")
-1
>>>

Peter




More information about the Python-list mailing list