Sorting A List In Python
Solution 1:
You could do it in one line, with:
sorted(words, key=lambda x: 'a' + x if x.startswith('s') else'b' + x)
The sorted()
function takes a keyword argument key
, which is used to translate the values in the list before comparisons are done.
For example:
sorted(words, key=str.lower)
# Will do a sort that ignores the case, since instead# of checking 'A' vs. 'b' it will check str.lower('A')# vs. str.lower('b').sorted(intlist, key=abs)
# Will sort a list of integers by magnitude, regardless# of whether they're negative or positive:# >>> sorted([-5,2,1,-8], key=abs)# [1, 2, -5, -8]
The trick I used translated strings like this when doing the sorting:
"hello" => "bhello"
"steve" => "asteve"
And so "steve" would come before "hello" in the comparisons, since the comparisons are done with the a/b
prefix.
Note that this only affects the keys used for comparisons, not the data items that come out of the sort.
Solution 2:
1 . You can use generator expression
inside sorted
.
2 . You can use str.startswith
.
3 . Don't use list
as a variable name.
4 . Use key=str.lower
in sorted.
mylist1 = sorted((i for i in words if i.startswith(("s","S"))),key=str.lower)
mylist2 = sorted((i for i in words ifnot i.startswith(("s","S"))),key=str.lower)
return mylist1 + mylist2
why str.lower
?
>>> "abc" > "BCD"True>>> "abc" > "BCD".lower() #fair comparisonFalse
Solution 3:
>>> l = ['z', 'a', 'b', 's', 'sa', 'sb', '', 'sz']
>>> sorted(l, key=lambda x:(x[0].replace('s','\x01').replace('S','\x01') if x else'') + x[1:])
['', 's', 'sa', 'sb', 'sz', 'a', 'b', 'z']
This key function replaces, for the purpose of sorting, every value starting with S
or s
with a \x01
which sorts before everything else.
Solution 4:
One the lines of Integer
answer I like using a tuple slightly better because is cleaner and also more general (works for arbitrary elements, not just strings):
sorted(key=lambda x : ((1if x[:1] in ("S", "s") else2), x))
Explanation:
The key
parameter allows sorting an array based on the values of f(item)
instead of on the values of item
where f
is an arbitray function.
In this case the function is anonymous (lambda) and returns a tuple where the first element is the "group" you want your element to end up in (e.g. 1 if the string starts with an "s" and 2 otherwise).
Using a tuple works because tuple comparison is lexicographical on the elements and therefore in the sorting the group code will weight more than the element.
Post a Comment for "Sorting A List In Python"