리스트

순서를 가지는 객체들의 집합, 파이썬 자료형들 중 가장 많이 사용

리스트 생성과 연산

  •     시퀀스 자료형 : 시퀀스 연산(인덱싱, 슬라이싱, 연결, 반복, len, in, not in) 가능
  •     변경 가능(mutable) 자료형이므로 항목의 추가, 변경, 삭제 모두 가능

 

1
2
3
4
5
6
7
8
9
= [12'python'# 리스트는 [ ] 기호를 이용하여 생성
print(l[-2], l[-1], l[0], l[1], l[2])
print(l[1:3])
print(l * 2)
print(l + [345])
print(len(l))
print(2 in l)
del l[0]
print(l)
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

 

 

리스트 : 항목의 변경 및 슬라이스를 이용한 치환

1
2
3
4
5
6
7
8
9
10
11
12
= ['apple''banana'1020]
a[2= a[2+ 90 # mutable 자료형 -> 항목 변경 가능
print(a)
# 슬라이스를 이용한 치환의 예
= [1121231234]
a[0:2= [1020]
print(a)
a[0:2= [10]
print(a)
a[1:2= [20]
print(a)
a[2:3= [
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

 

리스트 : 슬라이스를 이용한 삭제와 삽입

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 슬라이스를 이용한 삭제
= [1121231234]
a[1:2= [ ]
print(a)
a[0:] = [ ]
print(a)
# 슬라이스를 이용한 삽입
= [1121231234]
a[1:1= ['a']
print(a)
a[5:] = [12345]
print(a)
a[:0= [-12-10]
print(a)
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

리스트 : 리스트의 메서드

함수 설명
append(x) 리스트의 마지막에 x를 추가
insert(i, x) 리스트 인덱스 i 위치에 x를 추가
reverse() 리스트를 역순으로 뒤집음
sort() 리스트 요소를 순서대로 정렬
remove(i) 리스트 인덱스 i에 있는 요소를 제거
extend(l) 리스트 마지막에 리스트 l을 추가
index(x) 인덱스 내에 x가 있으면 인덱스값을 반환, 없으면 에러
count(x) 리스트 내에 x가 몇 개 있는지 그 개수를 반환

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
= [123]
print(a)
a.append(5)
print(a)
a.insert(34# 인덱스 3에 요소 4를 추가
print(a)
print(a.count(2)) # 리스트 내 요소 2의 개수를 반환
a.reverse()
print(a)
a.sort()
print(a)
a.remove(3# 내부에 있는 요소 3을 제거
print(a)
a.extend([678])
print(a)
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

 

리스트를 Stack(Last in, First out) 과 Queue(First in, First out) 로 사용하기

 

리스트의 append와 pop 메서드를 이용하여 스택을 구현할 수 있다.

1
2
3
4
5
6
7
8
stack = [ ]
print(stack)
print(stack)
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

 

리스트의 append와 pop 메서드를 이용하여 스택을 구현할 수 있다

1
2
3
4
5
6
7
8
queue = [ ]
print(queue)
print(queue.pop(0)) # 가장 앞쪽 인덱스의 요소를 pop
print(queue.pop(0))
print(queue)
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

 

sort 메서드 활용

sort 메서드의 reverse 를 True로 설정하면 역순으로 정렬할 수 있다

1
2
3
4
5
= [1539842]
l.sort()
print(l)
l.sort(reverse=True)
print(l)
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

키값 기반의 사용자 정의 정렬

1
2
3
4
5
= [102229833411]
l.sort(key = str)
print(l)
l.sort(key = int)
print(l)
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

 

+ Recent posts