1. Sort
- Only List(In-place)
- Reverse = [::-1]
a = [1,5,2,4]
a.sort()
> [1,2,4,5]
# a.sort() -> a[::-1]
a.sort(reverse=True)
> [5,4,2,1]
2. Sorted
- Use Iterable Object
- A simple ascending sort and returns a new sorted list
- key parameter call function for list element
#iterable dict
temp = {1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'}
sorted(temp)
> [1, 2, 3, 4, 5]
sorted(temp.items())
> [(1, 'D'), (2, 'B'), (3, 'B'), (4, 'E'), (5, 'A')]
sorted(temp.items() , key = lambda x:x[1] )
> [(5, 'A'), (2, 'B'), (3, 'B'), (1, 'D'), (4, 'E')]
# class example
class Student:
def __init__(self, name, grade, age):
self.name = name
self.grade = grade
self.age = age
def __repr__(self):
return repr((self.name, self.grade, self.age))
student_objects = [
Student('john', 'A', 15),
Student('jane', 'B', 12),
Student('dave', 'B', 10),
]
sorted(student_objects, key=lambda student: student.age)