-
확장 슬라이스(Extended Slices)Python 2021. 1. 5. 23:06반응형
리스트 슬라이싱
리스트이름[A:B:C] 같은 형태로 리스트 요소에 접근하는 방법
인덱스 A부터 인덱스 (B-1)까지 C만큼의 간격으로 리스트를 만들라는 뜻이다.
디폴트 값은 '처음부터 끝까지 1만큼의 간격' 이다.>>> list1 = [i for i in range(10)] >>> list2 = list1[::-1] >>> list2 [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
-1은 역순으로 한 칸씩을 의미한다.
>>> list3 = [i for i in range(10)] >>> list3 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> list3[2:8] [2, 3, 4, 5, 6, 7] >>> list3[2:8:2] [2, 4, 6]
인덱스 2부터 7(8-1)까지 2만큼의 간격으로 출력한다.
>>> list1 = [i for i in range(10)] >>> del list1[::2] >>> list1 [1, 3, 5, 7, 9]
del을 통해 삭제할 수 있다.
>>> title = 'LIAR LIAR' >>> title[::2] 'LA IR'
문자열이나 튜플에도 똑같이 적용된다.
참고
docs.python.org/ko/3/whatsnew/2.3.html?#extended-slices
What’s New in Python 2.3 — Python 3.9.1 문서
This article explains the new features in Python 2.3. Python 2.3 was released on July 29, 2003. The main themes for Python 2.3 are polishing some of the features added in 2.2, adding various small but useful enhancements to the core language, and expanding
docs.python.org
반응형'Python' 카테고리의 다른 글
정규표현식 re.sub() - 특정 문자열 교체 (0) 2023.04.06 값 입력 받기 (0) 2021.01.13 chr(x), ord(x) - a~z까지 아스키코드로 입력하기 (0) 2021.01.05 print문 안에 조건문 사용하기 (0) 2021.01.05 f-string (0) 2021.01.05