(지난 포스팅에 이어서)
2. Sequence
- range
적은 양의 데이터로 큰 수를 표현할 수 있다.
list, tuple같은 경우 n개의 데이터를 가지고 있으면 메모리도 실제로 그만큼 필요하지만
range은 실제데이터가 아닌 데이터 영역(range)에 대한 의미만 저장하기 때문에 작은 메모리공간으로 많은 데이터를 표현할 수 있다.
range(시작값, 마지막값-1, 증가값)
정수만값으로 가진다
a = range(0, 10, 1)
기본값으로 시작값은 0, 증가값은 1으로 생략하면 기본값으로 지정이되어 작동한다.
a = range(10)
a = range(0, 10)
이 두 선언은 위의 선언과 정확히 똑같은 의미를 가진다.
range와 함께 자주 쓰는 연산자로 in 연산자가있다.
in 연산자는 안에 들어있는가를 판단하고, 결과값으로 True or False를 가지는 논리연산자이다.
6 in range(10) ##True
range는 list와 비슷하게 indexing과 slicing도 가능하다.
a = range(10, 50, 1)
print(a[1]) ## 11
print(a[:10])
3. Text Sequence Type
string class str
python은 문자와 문자열을 구분하지 않는다
파이썬은 문자(character)의 개념이 없고 모두 문자열이다
- C와 Java와 같은 다른 언어에서는 문자는 1글자로 'a'를 사용하고, 문자열은 "aaa"를 사용한다.
하지만 python은 'aa', "a"도 구분없이 사용이 가능하다
하지만 관용적으로 ''을 이용한다
영어와 한글 모두 같은 방식으로 인식하는데 이는 내부적으로 유니코드를 이용하기 때문이다.
String은 내부적으로 리스트로 표현이 되어 리스트의 특성을 이용할 수 있다.
또 문자열은 많은 메소드를 가진다.
연산이 가능하다.
a = 'Hello' b = 'World!' print(a+b) ## HelloWorld!
Indexing과 Slicing도 가능하다.
a = 'this is a sample text' print(a[0]) ## t
in 연산자 사용
a = 'this is a sample text' print('sam' in a) #True print('haha' not in a) #False
문자열의 길이
a = ' 이것은 소리없는 아우성 ' len(a) ##18, 공백도 함께 센다
공백 제거
##앞뒤 공백 제거 print(a.strip()) ##이것은 소리없는 아우성 ##앞 공백 제거 print(a.lstrip()) ##이것은 소리없는 아우성 ##뒤 공백 제거 print(a.rstrip()) ## 이것은 소리없는 아우성
문자열 변경
a = 'show me the money' print(a.replace('money', 'code')) ## show me the code
문자열 중 일부를 치환할때는 format함수를 사용한다.
예시
num_banana = 20
num_apple = 7
a = '나는 바나나를 {}개 가지고 있고 사과를 {}개 가지고 있어요!'
print(a)
print(a.format(num_banana, num_apple))
##이렇게도 사용가능하다 a = '나는 바나나를 {}개 가지고 있고 사과를 {}개 가지고 있어요!'.format(num_banana, num_apple)
format함수를 이용하면
위의 예에서 num_banana와 num_apple의 값이 바뀌어도 a의 내용을 수정하지 않고 변경된 내용을 반영해 출력할 수 있다.
더 많은 속성은 공식 문서를 참고하자
API reference
string - Common string operations
4. Mapping Type
Dictionary class dict
literal : {'':''}
{}를 이용하고 key와 value의 쌍을 저장하는 집합자료구조. 순서가 없다
a = {
'name' : '홍길동',
'age' : 20,
'addr' : '서울'
}
print(a) #{'name': '홍길동', 'age': 20, 'addr': '서울'}
print(type(a)) #<class 'dict'>
값을 추가하려면?
a['mobile'] = '01012345678' print(a) ## {'name': '홍길동', 'age': 20, 'addr': '서울', 'mobile': '01012345678'}
값을 수정하려면?
a['age'] = 25 print(a) ## {'name': '홍길동', 'age': 25, 'addr': '서울', 'mobile': '01012345678'}
키값을 동일하게 작성하면??
a = { 'age' : 25,
'age' : 30
}
오류는 나지 않지만, 의미론적으로 틀리고 아무도 이렇게 사용하지 않는다.
또 두 값 중 하나만 사용할 수 있다.
키값으로 정수도 된다
a = { 10 : 'ten' }
키값으로 tuple은 사용이 가능하지만, list는 사용할 수 없다
why? 키 값은 변하면 안되기때문이다
- 모든 키값을 얻어내려면?
print(a.keys()) ## dict_keys(['name', 'age', 'addr', 'mobile'])
리스트처럼 생겼지만 리스트 객체는 아니다
= class list에서 나온 것이 아님, 리스트의 속성을 모두 이용할 수 있지 않음
진짜 리스트라면 ['name', 'age', 'addr', 'mobile'] 이렇게 출력되었을 것임
a.keys()[0] ##error
- 모든 value값을 얻으려면?
print(a.values()) ##dict_values(['홍길동', 25, '서울', '01012345678'])
딕셔너리의 메소드들
w3schools
w3schools가 보기에 더 편한 것 같다
5. Set type
set class set
여러 개의 데이터를 저장할 수 있는 집합 자료구조
키의 개념이 없고 값만 저장한다
- 순서가 없음
- 중복이 없음
literal :
{} (dictionary와 set은 둘 다 {} 사용)
set()
a = {'홍길동', '아이유', 20, '서울'}
print(type(a)) ## <class 'set'>
a = set()
print(type(a)) ## <class 'set'>
a = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
print(set(a)) ## {1, 2, 3, 4}
a = {'홍길동', '홍길동', '서울', '서울'}
print(a) ## {'홍길동', '서울'}
set의 연산
set은 집합의 개념으로 set의 연산은 집합의 연산과 개념이 같다.
- 합집합(Union) : |
- 교집합(Intersection) : &
- 차집합(Difference) : -
a = set([1, 2, 3, 4, 5])
b = set([3, 4, 5, 6, 7])
##합집합 |
union = a | b
print(union) # {1, 2, 3, 4, 5, 6, 7}
##교집합 &
intersection = a & b
print(intersection) # {3, 4, 5}
##차집합 -
difference = a - b
print(difference) # {1, 2}
요소 추가
add : 한 개 씩 추가
a.add(6) print(a) # {1, 2, 3, 4, 5, 6} a.add('안녕') print(a) # {1, 2, 3, 4, 5, 6, '안녕'} a.add((7,)) print(a) # {1, 2, 3, 4, 5, 6, '안녕', (7,)}
update : 여러 개 한 번에 추가
a.update([10, 11, 12]) print(a) # {1, 2, 3, 4, 5, 6, '안녕', 10, 11, 12, (7,)}
요소 제거
a.remove('안녕') print(a) # {1, 2, 3, 4, 5, 6, 10, 11, 12, (7,)}
6.Bool type
boolean class bool
True 또는 False 값만 가지는 논리 타입이다.
연산자는 and, or, not 세 가지가 있다
print(True and False) # False
print(True and True) # True
print(True or False) # True
print(not True) #False
print(type(True)) # <class 'bool'>
- 무조건 False로 간주되는 값들을 알아두어야 한다.
- empty string
- [], (), {}
- 숫자 0 (숫자 1은 True 간주된다)
- None
'Programming > Python' 카테고리의 다른 글
[python] 함수 (0) | 2022.01.21 |
---|---|
[python] 제어문 Control Statement (0) | 2022.01.20 |
[python] id()함수과 숫자 객체의 메모리 주소 값 (0) | 2022.01.19 |
[python] 데이터타입 1 - Numeric과 Sequence (0) | 2022.01.19 |
[Python] 주석 처리 방법과 변수 (0) | 2022.01.19 |