본문 바로가기
대학원 공부/programming language

Python : basic : list.sort(), sorted

by 월곡동로봇팔 2019. 11. 22.

list.sort()


list.sort()는 list를 sort해서 list에 다시 저장하는 느낌이다.

즉 list = sorted(list) 라고 생각하면 어렵지 않다.

 

 

sorted( list_name, 조건(key 값을 다르게 준다, Descending or Ascending) )


# 공백을 기준으로 문자열을 나누어 리스트로 변환한다
# 리스트로 변환시
>>> sorted("This is a test string from Andrew".split(), key=str.lower)

['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']

뒤에 key를 str이 lower한 것 부터대로 sort하는 것을 의미한다.

 

 

sorted를 복잡한 객체를 정렬할 때 자주 사용

 


>>> student_tuples = [
...     ('john', 'A', 15),
...     ('jane', 'B', 12),
...     ('dave', 'B', 10),
... ]
>>> sorted(student_tuples, key=lambda student: student[2])   
# sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

student_tuples를 뒤에 숫자들로 정렬하고 싶을 때 사용한다.

 

아마도 data가 json이나 다른 list of list를 다룰 때 용이하게 쓰일 것으로 생각된다.

댓글