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.
Answer from integer on Stack OverflowVideos
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.
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 if not i.startswith(("s","S"))),key=str.lower)
return mylist1 + mylist2
why str.lower?
>>> "abc" > "BCD"
True
>>> "abc" > "BCD".lower() #fair comparison
False
No need to import anything when using lambda functions.
The following sorts list by the first element, then by the second element. You can also sort by one field ascending and another descending for example:
sorted_list = sorted(list, key=lambda x: (x[0], -x[1]))
like this:
import operator
list1 = sorted(csv1, key=operator.itemgetter(1, 2))
lst=[(11, "Jenny"),(8, "Adam"),(10, "Mark"),(8, "Ada")]
lst.sort(key=lambda x: (-x[0],len(x[1])) )
print (lst) # [(11, 'Jenny'), (10, 'Mark'), (8, 'Ada'), (8, 'Adam')]
The list method sort and the builtin function sorted accept a keyword argument key which is given a callable. Basically, for every element in the sequence, that element is passed to the key function and the return value of that function is actually what python uses to determine ordering when sorting. So, in the above, I use lambda to construct a function which returns a tuple from the input elements. The tuple is ordered first_element, lenth_of_second_element.
When tuples (or lists for that matter) are compared, it's much like comparing a string. You look at the first element, if they're the same, you continue on to look at the second element, then the third and so on until one element is greater than the other. e.g.
(1,2,3,4) > (1,2,3,3) #True
This ends up being handy for sorting in very interesting ways.
I suppose to round this out, I should mention that the algorithm that python uses to sort is stable. This means that if you sort by keyA and then you sort by keyB, two elements which compare equal based on keyB will maintain the order they had after the sort using keyA. In other words, a sort doesn't change the order of equal valued elements. So, the above could also be accomplished like this:
lst.sort(key=lambda x:len(x[1])) #sort by length of names
lst.sort(key=lambda x:x[0], reversed=True) #sort by score (highest first instead of regular lowest first)
And I suppose no answer is complete without a link to something which explains it more elegantly. (Specifically, see the section on "Key Functions")
You'd have to iterate over each line and use the sort method on them
#open the file and read through the lines.
lines = open('yourfile.txt').readlines()
#iterate over each line, and split along the spaces
pairs =[]
for line in lines:
split_string = line.split('')
num = int(split_string[0])
pairs.append((num, split_string[1:])
#sort through the pairs (from mgilsons answer)
pairs.sort(key=lambda x: (x[0],len(x[1]))
edit: actually misread the question.