Notice
Recent Posts
Recent Comments
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
10-10 22:21
Archives
Today
Total
관리 메뉴

Developer_Neo

[python] 인덱싱(indexing), 슬라이싱(slicing) with 문자열, 리스트, 튜플 본문

카테고리 없음

[python] 인덱싱(indexing), 슬라이싱(slicing) with 문자열, 리스트, 튜플

_Neo_ 2022. 1. 16. 11:38
반응형

인덱싱(indexing)

- 시퀀스 자료형인 문자열, 리스트, 튜플에 사용가능

- 시퀀스 자료형에 부여된 번호를 의미한다. 

특징

  • 양수 인덱스
    • 앞에서부터 시작하는 것으로 0부터 시작
  • 음수 인덱스
    • 뒤에서부터 시작하는 것으로 -1부터 시작

문자열

a = 'hello'
print(a[0]) # 결과 값: h
print(a[1]) # 결과 값: e
print(a[2]) # 결과 값: l
print(a[3]) # 결과 값: l
print(a[4]) # 결과 값: o

print(len(a))  # 결과 값: 5
0 1 2 3 4
h e l l o
-5 -4 -3 -2 -1

- 양수 인덱스의 맨 마지막은 len(a)-1 이라고 할 수 있고 음수인덱스의 맨 앞은 -len(a)라고 할 수 있다.

 

리스트

>>> s = 'show how to index into sequences'.split()
>>> s
['show', 'how', 'to', 'index', 'into', 'sequences']
>>> s[0]
'show'
>>> s[5]
'sequences'
>>> s[-1]
'sequences'
>>> s[-2]
'into'
>>> s[-6]
'show'

출처 https://wikidocs.net/16037

 

11. List(리스트)(2) - 리스트 인덱싱, 리스트 슬라이싱

## 1.list indexing(리스트 인덱싱) - 파이썬에서 리스트 인덱싱은 `-`(음수 인덱싱) 값도 허용합니다. - `-` 값은 역순으로도 인덱싱됩니다. - 다른 ...

wikidocs.net

튜플

tuple=(1,2,3,4,5)
print(tuple[0]) #결과: 1
print(tuple[3]) #결과: 4
print(tuple[5]) 
'''결과: 
Traceback (most recent call last):
  File "<pyshell#15>", line 1, in <module>
    print(tuple[5])
IndexError: tuple index out of range
'''
print(tuple[-1]) #결과: 5
print(tuple[-2]) #결과: 4
print(tuple[-5]) #결과: 1

 

 

슬라이싱(slicing)

- 시퀀스 자료형인 문자열, 리스트, 튜플에 사용가능

- 부여된 번호를 이용해 일부를 추출하는 작업이다.

- 변수[start:end:step] 형식

    start부터 시작해서 인덱스 end전까지 슬라이싱

- 변수[start:end]

   start부터 시작해서 인덱스 end전까지 step간격으로 슬라이싱

문자열

a = 'hello'
print(a[0:3]) # 결과 값: hel
print(a[0:4:2]) # 결과 값: hl
print(a[0:4:-1]) # 결과 값: 
print(a[-1:-4:-1]) # 결과 값: oll
print(a[-1:-4]) # 결과 값:
print(a[:]) # 결과 값hello

step부분의 기본값은 양수인 1로 되어있다 그래서 뒤에서부터 출력되길 원한다면 step에 음수를 적어주어야한다.

 

리스트

>>> s = 'show how to index into sequences'.split()
>>> s
['show', 'how', 'to', 'index', 'into', 'sequences']
>>> s[::2]
['show', 'to', 'into']
>>> s[::-1]
['sequences', 'into', 'index', 'to', 'how', 'show']
>>> s[1:4]
['how', 'to', 'index']
>>> s[3:]
['index', 'into', 'sequences']

 

튜플

tuple=(1,2,3,4,5,6)
print(tuple[1:4]) #결과: (2, 3, 4)
print(tuple[1:5:2]) #결과: (2, 4)
print(tuple[:]) #결과: (1,2,3,4,5,6)
print(tuple[::-1]) #결과: (6, 5, 4, 3, 2, 1)
print(tuplea[-1:-6:-3]) #결과: (6, 3)
반응형
Comments