On 02/04/2016 06:51, Michael Selik wrote:
On Sat, Apr 2, 2016, 1:46 AM Vito De Tullio <vito.detul...@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.


My gut feeling about how fast something is in Python has never once been right in 15 years. There is only way way to find out, measure it with things like https://docs.python.org/3/library/profile.html and https://docs.python.org/3/library/timeit.html. IIRC Steven D'Aprano has a wrapper for the latter called Stopwatch.

--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to