Drowning in a teacup?
Michael Selik
michael.selik at gmail.com
Sat Apr 2 01:51:46 EDT 2016
On Sat, Apr 2, 2016, 1:46 AM Vito De Tullio <vito.detullio at gmail.com> wrote:
> 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']
>
If the number of matches is small relative to the size of the list, I'd
expect the sort would be slower than most of the other suggestions.
>
More information about the Python-list
mailing list