python_sort

Python sorting

sorted() : returns a new list
list.sort() : modifies the list in-place and only defined for list

Let’s look at some example :

using sorted()

1
2
3
example = [7,4,3,1,2]
sorted(example)
print(example)

example not ordered after calling sorted:
output : 7, 4, 3, 1, 2

1
2
after_sort = sorted(example)
print(after_sort)

assign to new list after_sort
output : 1, 2, 3, 4, 7

using list.sort()

1
example.sort()

output is sorted : 1, 2, 3, 4, 7

using itemgetter()

1
2
3
4
from operator import itemgetter
student = [["D",10],["C",10],["B",10],["A",10],["G",4]]
student.sort(key=itemgetter(1,0))
print(student)

first order by number (itemgetter(1))
then order by alphabet ( itemgetter(0))
output : [[‘G’, 4], [‘A’, 10], [‘B’, 10], [‘C’, 10], [‘D’, 10]]

hackerrank :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from operator import itemgetter
store_stu = []
min = 1000
if __name__ == '__main__':
for _ in range(int(input())):
name = input()
score = float(input())
if score < min:
min = score
store_stu.append([name,score] )
store_stu = sorted(store_stu, key = itemgetter(1,0) )
flag_small = 0
for i,j in store_stu:
if j > min and flag_small==0:
flag_small = j
if flag_small == 0:
flag_small = min
for i,j in store_stu:
if j == flag_small:
print(i)
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×