빅데이터 전문가 되기
시퀀스 자료형(sequence types) 본문
👀 시퀀스 자료형(sequence types)?
: 연속적으로 이어진 자료형
ex) list, str, tuple, range, bytes, bytearray..
- 특징
① 공통된 동작과 기능을 제공한다.
② 시퀀스 자료형으로 만든 객체를 시퀀스 객체라 부르며, 객체 안에 저장된 값을 요소라 부른다.
③ 반복문이 사용 가능하다.
👉 검색: 특정 값이 있는지 확인 ( 값 in 시퀀스 객체 )
dic = { "one":1, "two":2, "three":3 }
if( 1 not in dic.values() ):
print('1 not in dic')
else:
print("1 in dic")
1 in dic
→ 시퀀스 객체에 존재하는 경우 True를 반환하고, 없다면 False를 반환한다.
여기서 1은 시퀀스 객체에 존재하므로 '1 in dic' 를 출력한다.
👉 결합: 시퀀스 객체의 결합
num1=[10, 20]
num2=[30, 40]
num3=(50, 60)
#서로 다른 형태의 시퀀스는 연산 불가
#num = num1+num3
n1 = num1 + num2
n2 = num1 + list(num3)
print(n1)
print(n2)
[10, 20, 30, 40]
[10, 20, 50, 60]
→ 같은 시퀀스 자료형일 경우만 연산이 가능하며, 서로 다른 시퀀스 자료형일 경우 형변환이 필요하다.
👉 길이: 시퀀스 객체의 요소 개수 구하기
list = [1,2,3,4,5]
tuple = ("one", "two", "three")
dic = {1:"one", 2:"two", 3:"three"}
print(len(list))
print(len(tuple))
print(len(dic))
number = range(1,10,2)
print(len(number))
hello = "안녕하세요"
print(len(hello))
print(len(hello.encode("utf-8")))
5
3
3
5
5
15
→ 문자열의 길이는 공백을 포함한다.
인코딩 방법에 따라서 문자 하나가 가지는 크기(byte)가 다르다.
👉 isinstance 함수를 활용하여 데이터 타입 확인
- isinstance ( 확인하고자하는 데이터 값, 확인하고자 하는 데이터 타입)
- 반환값 : True, False
from collections.abc import Sequence
my_num = 100
my_list = [1,2,3]
my_string = "hello"
isSeq1 = isinstance(my_num, Sequence)
print(isSeq1)
isSeq2 = isinstance(my_list, Sequence)
print(isSeq2)
isSeq3 = isinstance(my_string, Sequence)
print(isSeq3)
False
True
True
'Python' 카테고리의 다른 글
사용자 정의 함수 (4) | 2023.04.13 |
---|---|
List 요소 삭제 (0) | 2023.04.13 |
Immutable 과 Mutable (0) | 2023.04.13 |
Python 자료 모음 (0) | 2023.04.13 |
Python_list comprehension (2) | 2023.04.13 |
Comments