What is the best way to sort a list with custom sort options in Python?

I have a number of lists that look like this:

li1 = ['a.1', 'b.9', 'c.8', 'd.1', 'e.2'] li2 = ['a.4', 'b.1', 'c.2', 'd.2', 'e.4'] 

How can I reorder the items in each list so that the first item is "b.something"? For the example above:

 li1 = ['b.9', 'a.1', 'c.8', 'd.1', 'e.2'] li2 = ['b.1', 'a.4', 'c.2', 'd.2', 'e.4'] 

Keeping order after the first element is not important. Thanks for the help.

+6
source share
3 answers

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.

+4
source

Python's sorting is stable, so you'll keep order after the first element independently.

 li1.sort(key=lambda x: not x.startswith('b.')) 
+5
source

You can use sorted , which takes a key argument and returns a list:

 >>> li1 = ['a.1', 'b.2', 'c.8'] >>> def k(s): ... if s.startswith('b.'): ... return 1 ... else: ... return 2 ... >>> sorted(li1, key=k) ['b.2', 'a.1', 'c.8'] 

k should return what can be compared between the elements to be destroyed.

Note: sort changes the input in place and returns nothing when sorted returns a sorted list and does not change your list. Both work the same way.

+3
source

Source: https://habr.com/ru/post/900702/


All Articles