프로그래밍/Python

자료형 및 연산자

MAKGA 2021. 8. 7. 15:39
320x100

 

수치

int, long, float, complex등

 

문자

str

 

리스트

값의 나열이다. 순서가 존재하며, 여러 종류의 값을 담을 수 있다

0부터 시작하는 인덱스가 있으며, 슬라이싱도 가능하다.

// 리스트 생성
colors = ['red', 'green', 'gold']

// 리스트 항목 추가
colors.append('blue')

// 중간에 항목 삽입
colors.insert(1, 'black')

// 다중 삽입
colors.extend(['white', 'gray'])

// 항목 추가
colors += ['red']

// 항목 위치 찾기
colors.index('red')
colors.index('red',1) // 시작점 추가

// 원소 갯수
colors.count('red')

// 맨 마지막 항목 추출
colors.pop()

// 항목 삭제
colors.remove('gold')

// 정렬
colors.sort()
colors.reverse()

def mySort(x):
	return x[-1]
colors.sort(key=mySort)
colors.sort(key=mySort, reverse=True)

 

세트

값의 모임이며, 순서는 없다. { }로 묶어서 정의한다.

a = {1, 2, 3}
b = {4, 5}

// 합집합
a.union(b)
a | b

// 교집합
a.intersection(b)
a & b

// 차집합
a - b

 

튜플

리스트와 유사하지만 ()로 묶어서 표현하며, 읽기 전용이다.

a, b = 1, 2
(a, b) = (1, 2)

// swap
a, b = b, a

 

상호 변환 또는 찾기

a = set((1, 2, 3))
b = list(a)
c = tuple(b)

1 in a // True
2 in b // True
4 in c // False

 

사전

키와 쌍으로 구성돼있으며, 다음과 같이 정의한다.

서로 다른 자료형도 삽입이 가능하다.

// 생성
d = dict(a=1, b=3, c=5)
// 생성2
color = {"apple":"red", "banana":"yellow"}

// 항목 추가
color["cherry"] = "red"
colo

// 찾기
for c int colors.items():
	print c
// ('cherry', 'red') ...

for k, v in colors.items():
	print(k, v)
// cherry red ...

for k in colors.keys():
	print(k)
// cherry ..

// 삭제
del color['cherry']

// 전체 삭제
color.clear()

 

부울

True와 False를 가진다.

320x100