Drowning in a teacup?
Vito De Tullio
vito.detullio at gmail.com
Sat Apr 2 01:45:31 EDT 2016
Fillmore wrote:
> I need to scan a list of strings. If one of the elements matches the
> beginning of a search keyword, that element needs to snap to the front
> of the list.
I know this post regards the function passing, but, on you specific problem,
can't you just ... sort the list with a custom key?
something like (new list)
>>> sorted(['no_a', 'yes_c', 'no_b', 'yes_z', 'no_y', 'yes_x'],
... key=lambda e: not e.startswith('yes'))
['yes_c', 'yes_z', 'yes_x', 'no_a', 'no_b', 'no_y']
or (in place)
>>> l = ['no_a', 'yes_c', 'no_b', 'yes_z', 'no_y', 'yes_x']
>>> l.sort(key=lambda e: not e.startswith('yes'))
>>> l
['yes_c', 'yes_z', 'yes_x', 'no_a', 'no_b', 'no_y']
--
By ZeD
More information about the Python-list
mailing list