[파이썬] 리스트 다루기-3

조은지·2021년 5월 1일
0

출처 - https://www.w3schools.com/python/python_lists_methods.asp
출처 - https://dailyheumsi.tistory.com/67

리스트 메소드 정리

MethodDescription
append()Adds an element at the end of the list
clear()Removes all the elements from the list
copy()Returns a copy of the list
count()Returns the number of elements with the specified value
extend()Add the elements of a list (or any iterable), to the end of the current list
index()Returns the index of the first element with the specified value
insert()Adds an element at the specified position
pop()Removes the element at the specified position
remove()Removes the item with the specified value
reverse()Reverses the order of the list
sort()Sorts the list

리스트 정렬

  • reverse: 리스트를 거꾸로 뒤집는다. desc정렬이 아님
  • sort: 정렬, 기본 값은 오름차순 reverse=True는 내림차순 정렬
    sort의 key옵션: key 옵션에 지정된 함수의 결과에 따라 정렬
>>> m = '나는 파이썬을 잘하고 싶다'
>>> m = m.split()
>>> m
['나는', '파이썬을', '잘하고', '싶다']
>>> m.sort(key=len) #길이를 기준으로 오름차순 정렬
>>> m
['나는', '싶다', '잘하고', '파이썬을']

#람다식을 이용해 key를 설정할 수 있다. (아이템 첫번째 인자를 기준으로 오름차순 정렬한다)
a = [(1, 2), (0, 1), (5, 1), (5, 2), (3, 0)]
c= sorted(a, key = lambda x : x[0])
>>>c
[(0, 1), (1, 2), (3, 0), (5, 1), (5, 2)]

0개의 댓글

관련 채용 정보