reorder items in each list so that the first item is "b.something"
Keeping order after the first element is not important.
This is not a sort. It is clear that you are simply trying to bring this element to the forefront.
In other words, you need a list consisting of this element, followed by everything that is not this element. Massaging it a bit for the case when there are several b.something s, and noting that we don't care what happens as long as the first element is b.something , we can rephrase this: a list of each element that satisfies the condition ("begins with b. "), followed by each element that does not meet the condition. (This is sometimes called partitioning; see, for example, std::partition in C ++.)
In Python, it is as simple as describing and merging these two components of a combo box:
[x for x in li if x.startswith('b.')] + [x for x in li if not x.startswith('b.')]
... Or you can pretend to sort, just with a bunch of elements that really only have two values โโafter applying key and apply the corresponding key , as in Ignacio Vasquez-Abrams' answer.
source share