On Sat, Apr 2, 2016, 1:46 AM Vito De Tullio <[email protected]> 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.
>
--
https://mail.python.org/mailman/listinfo/python-list