Sequence

이상우·2022년 6월 16일
0

A sequence is a positionally ordered collection of items. And you can refer to any item in the sequence by using its index number e.g., s[0] and s[1] . In Python, the sequence index starts at 0, not 1. So the first element is s[0] and the second element is s[1] .
python sequence 참고

파이썬에서는 데이터 타입을 두가지로 나뉜다. 1.컨테이너(Contatiner: 서로다른 자료형[List, tuple, collections.deque]) 2.플랫(Flat: 한개의 자료형 [str, bytes, bytearray, array.array, memoryview])으로 나뉜다.
또한 가변형과 불변형으로 나눌 수 있다. 가변형에는 List, bytearray, array.array, memoryview, deque가 있고, 불변형에는 tuple, str, bytes로 나눌 수 있다.

지능형 리스트(Comprehending Lists)

chars = '+_)(*&^%$#@!'
code_list1 = []

for s in chars:
	#유니코드 리스트
	code_list1.append(ord(s)) #

print(code_list1)

#Comprehending Lists
code_list2 = [ord(s) for s in chars]

print(code_list2)

# Comprehending Lists + Map , Filter
code_list3 = [ord(s) for s in chars if ord(s) > 40]
# 이와 비슷하게 map함수를 써서 하는 방법
code_list4 = list(filter(lambda x: x > 40, map(ord, chars)))

# 결과 동일
print(code_list3)
print(code_list4)

Generator 생성

import array # array는 플랫형이고 가변이 가능하다

# generator : 한 번에 한 개의 항목을 생성(메모리 유지X)
tuple_g = (ord(s) for s in chars) # tuple_g 라는 generator 생성
print(tuple_g) #default tuple 전체가 출력이 안됨

리스트 주의

marks1 = [['~'] * 3 for _ in range(4)]
marks2 = [['~'] * 3] * 4

print(marks1)
print(marks2)
#두 리스트 결과값은 같다.


# 수정
marks1[0][1] = 'x'
marks2[0][1] = 'x'
# 결과값이 다르다. 

# 증명
print([id(i) for i in marks1])
print([id(i) for i in marks2])
# 왜냐하면 marks1에 각 리스트값은 아이디값이 다르지만, marks2는 각 리스트값이 동일하기 때문이다.

불변형 자료구조를 재정의한다면 새로운 아이디에서 저장을 하고, 가변형의 자료구조를 재정의한다면 같은 아이디값에서 저장을 한다.

List vs Array 적합 한 사용법

리스트 기반 : 융통성, 다양한 자료형, 범용적 사용
숫자 기반 : 배열(리스트와 거의 호환가능)

profile
구상한것을 구현할 수 있는 개발자가 되고 싶습니다.

0개의 댓글