본문 바로가기
Python

연속형 데이터 연습

by Nirah 2023. 1. 16.

연속형 데이터(Sequential Data Types)

하나의 변수가 여러개의 데이터를 가지고 있는 데이터 타입. (1:1숫자형 데이터와 반대개념)

리스트, 튜플, 스트링, 셋, 딕셔너리 등이 해당된다.

인덱싱과 슬라이싱의 개념을 익히는 것이 중점이다.

 

 

List

기능, 요소 추가 제거

리스트의 특징
리스트는 collection의 일종으로 , 다음과 같은 특징을 가지고 있습니다.
리스트는 대괄호로 둘러싸여 있고, 리스트 원소는 콤마 으로 구분됩니다
리스트는 파이썬의 어떤 객체도 원소로 넣을 수 있습니다.(다른 컬렉션도 가능)
빈 리스트를 생성할 수 있습니다.
번호(Index Number)에 의해 접근 가능
Iterable Type : 반복 가능 자료형으로 for 반복문에 의해 사용 할 수 있는 
자료형
Mutation Type : 변경 가능, 리스트 자료의 요소를 추가/수정/삭제 할 수 있다.

list_1 = []
print(type(list_1))

list_1 = [1,2,3,4]
print(type(list_1))

list_1 = list((1,2,3,4))
print(type(list_1))

# Unpacking
list_1 = [1,2,3]
list_1_1,list_1_2,list_1_3 = list_1
print(list_1_1,list_1_2,list_1_3)

#slicing
list_1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(list_1[0], list_1[-1]) #1 0
print(list_1[:3], list_1[-3:])#[1, 2, 3] [8, 9, 0]

#N차 리스트
list_1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(list_1[0][2], list_1[1][1], list_1[2][0])

# indexing, Slicing을 사용하여 요소 수정
list_1 = [1, 2, 3]
print(list_1)

list_1[0] = 'a'
print(list_1)

list_1 = [1, 2, 3]
print(list_1)
list_1[0:2] = 'a', 'b'
print(list_1)

# 리스트자료형 + 요소 추가
list_1 = []
list_1 = list_1 + [1, 2, 3]
print(list_1) #[1, 2, 3]
list_1[3:] = [4, 5, 6, 7]
print(list_1) #[1, 2, 3, 4, 5, 6, 7]

print(dir(list_1))

# append(value) : 리스트의 마지막 요소에 value를 추가 한다.
list_1 = []
list_1.append(1)
list_1.append('a')
list_1.append(['b'])
print(list_1)#[1, 'a', ['b']]

# extend(iterable) : 리스트의 마지막 요소에 
# iterable의 요소들을 추가 한다.
list_1 = []
list_1.extend('abcd')
list_1.extend([1, 2, 3])
print(list_1) #['a', 'b', 'c', 'd', 1, 2, 3]

# insert(index, value) : 리스트의 index 위치에 value를 추가 한다.
list_1 = [1, 2, 3]
list_1.insert(1, 'a')
list_1.insert(2, 'b')
list_1.insert(4, ['c', 'd'])
print(list_1) #[1, 'a', 'b', 2, ['c', 'd'], 3]

# pop([index]) : 리스트의 마지막 요소 값을 반환 후 삭제
# index 값이 주어지는 경우 index 위치의 값을 반환 후 삭제
list_1 = ['a', 'b', 'c', 'd']
a = list_1.pop()
b = list_1.pop(1)
print(list_1, a, b)     #['a', 'c'] d b (각각 리스트1, a, b)

# remove(value) : 리스트의 요소 중 value에 해당하는 요소 삭제
list_1 = ['a', 'b', 'c', (1, 2), 'd']
list_1.remove('b')
list_1.remove((1, 2))
print(list_1) #['a', 'c', 'd']

# list del functions
list_1 = ['a','b','c',(1,2),'d']
list_2 = list_1.copy()
print(f'Original : {list_2}')
del list_2[0]
print(f'After delete : {list_2}')


# clear() : 리스트의 모든 요소 삭제
list_1 = [1, 2, 3]
list_1.clear()
print(list_1) # []


# list copy functions
list_1 = ['a','b','c',(1,2),'d']
list_2 = list_1
print(list_1 is list_2) # True 할당개념
print(id(list_1),id(list_2))

 
list_2 = list_1.copy()
print(list_1 is list_2) # False 복사개념
print(id(list_1),id(list_2))


# count(value) : 리스트의 요소 중 value에 해당하는 요소 수 반환
list_1 = [1, 2, 3, 1, 2, 1]
print(list_1.count(1)) # 3

# index(value[, start_index]) : 
# 리스트의 요소 중 value에 해당하는 요소의 index 반환, 
# start_index를 지정하면 start_index 부터 찾는다.
list_1 = [1, 2, 3, 1, 2, 1]
print(list_1.index(1)) # 0
print(list_1.index(1, 1)) # 3

# reverse() : 반전, 리스트 요소의 순서를 거꾸로 뒤집는다.
list_1 = ['a', 'b', 'c', 'd']
list_1.reverse()
print(list_1) # ['d', 'c', 'b', 'a']

# sort([reverse=True]) : 정렬, 리스트의 요소를 오름차순으로 정렬 한다. reverse=True를 사용하면 내림차순으로 정렬 한다. 정렬 할 때 문자열/정수, 문자열/실수 간의 정렬은 안된다.
list_1 = ['g', 't', 'u', 'c']
list_1.sort()
print(list_1)#['c', 'g', 't', 'u']
list_1.sort(reverse=True)
print(list_1)#['u', 't', 'g', 'c']

list_1 = ['God is love','ABC']
print(len(list_1))
list_1 = ['God', 'is', 'love']
print(len(list_1)) # 3


friends = ['Joseph','Glenn','Sally']
for friend in friends :
  print('Happy new year:', friend)
for i in range(len(friends)):
  friend = friends[i]
  print('Happy new year:',friend)
  
list_1 = [1,2,3]
list_2 = [4,5,6]
list_3 = list_1 + list_2
print(list_3) #[1, 2, 3, 4, 5, 6]
  
# in , not in : 리스트 원소 탐색
# 파이썬에서는 특정원소가 리스트에 있는지 확인할 수 있는 
# 2가지 연산자를 제공합니다.
# True, False를 반환하는 논리연산자입니다.
 
list_1 = [1,9,21,10,16]
print(9 in list_1) #True
print(15 in list_1) # False
print(20 not in list_1) #True

list_1 = [1, 2, 3, 4, 5]
print(f'The sum of numbers within list_1 is {sum(list_1)}.')
print(f'The max of numbers within list_1 is {max(list_1)}.')
print(f'The min of numbers within list_1 is {min(list_1)}.')
print(f'The average of numbers within list_1 is {sum(list_1)//len(list_1)}.')

list_1 = [1, 2, 3, 4, 5]
total = 0
for cnt in range(len(list_1)):
  total = total + list_1[cnt]
print(f'The sum of numbers within list_1 is {total}.')

 

 

tuple

튜플은 리스트와 비슷하게 인덱싱, 슬라이싱 등을 지원한다.

차이점이 있다면 리스트는 [] 대괄호, 튜플은 ()소괄호 를사용하고

리스트는 생성후 원소 등을 변경가능, 튜플은 생성후 변경불가다.

slicing
    tuple_1 = (1, 2, 3, 4, 5, 6, 7)
    print(tuple_1[0],tuple_1[-1]) # 1,  7
    print(tuple_1[0:3]) # (1, 2, 3)
    print(tuple_1[:3]) # (1, 2, 3)
    print(tuple_1[3:]) # (4, 5, 6, 7)
    print(tuple_1[3:-1]) # (4, 5, 6)
    print(tuple_1[-1]) # 7
    print(tuple_1[-2]) # 6
    print(tuple_1[-3:]) # (5, 6, 7)
    print(tuple_1[:-3]) # (1, 2, 3, 4)

tuple_1 = (1,2,3,1,2,1)
    print(tuple_1.index(1)) # 0
    print(tuple_1.index(1,1)) # 3

tuple_1 = ('c','d','a','e','b')
    print(len(tuple_1)) # 5

tuple concatenate
    tuple_1 = (1,2,3)
    tuple_2 = (4,5,6)
    tuple_3 = tuple_1 + tuple_2
    print(tuple_3) # (1, 2, 3, 4, 5, 6)

tuple_1 = (1, 2, 3, 4, 5)
  print(f'The sum of numbers within tuple_1 is {sum(tuple_1)}.')
  print(f'The max of numbers within tuple_1 is {max(tuple_1)}.')
  print(f'The min of numbers within tuple_1 is {min(tuple_1)}.')
  print(f'The average of numbers within tuple_1 is {sum(tuple_1)//len(tuple_1)}.')

 

 

Dictionary

아래와 같은 테이블 컨셉을 의미하며 key값과 value값 개념을 통해 저장된다. (key-value 방식)

name code
raid1 2022
raid0 2023

정수 index가 아닌 key값을 통해서 value에 엑세스 한다.

이 방식의 장점은 순서가 아닌 의미가 있는 값을 통해 데이터 접근이 가능하다는 것이다(태그?) (리스트랑 비교해보라)

딕셔너리의 표현 방식은 {} 중괄호를 사용하며, 집합과 차이를 두기 위해 원소에 key:value 형식으로 콜론을 쓴다.

예시 {'a':1,"b":3}

 

 

 

https://blog.naver.com/goodse7/222661296996

 

 

Dictionary(사전) 자료형
 
특징
Mapping Type : Sequence Type과 다르게 Index를 사용하지 않고
Key를 Index 처럼 사용 한다.
Iterable Type : 반복 가능 자료형으로 for 반복문에 의해 사용
할 수 있는 자료형
Mutation Type : 변경 가능, 사전 자료의 요소를 추가/수정/삭제
할 수 있다.
딕셔너리는 다른 언어의 해시 테이블( hash table ) 또는 맵( map )과 같습니다.
딕셔너리의 각 원소는 key와 value를 하나의 쌍으로 하여 형성됩니다.
 
생성 방법(Syntax)
{} 중괄호를 사용하여 생성 한다.
d = {}  # 빈 사전형
항상 Key와 Value의 쌍으로 생성해야 한다.
Key로 사용 할 수 있는 자료형은 정수, 실수, 문자열, 튜플 이다.
Key는 중복이 될 수 없다. 하나의 Key만 사용 가능
Value로 사용 할 수 있는 자료형은 모든 자료형 이다.
{Key:value, ...}
d = {'name':'Python', 'version':3.6}
 
사전형 자료에 접근하는 방법
딕셔너리를 생성하는 여러가지 방법
fruit = {'apple': 100, 'banana': 50}
print(type(fruit))          # <class 'dict'>

dict() 함수의 인자로 key=value를 전달
d = dict(apple=100, banana=50)
print(d, type(d))           # {'apple': 100, 'banana': 50} <class 'dict'>

dict() 함수의 인자로 리스트, 튜플을 원소로 갖는 리스트를 전달
d2 = dict([['apple', 100], ['banana', 50]])
print(d2, type(d2))
 
d2 = dict([('apple', 100), ('banana', 50)])
print(d2, type(d2))
 
d2 = dict((('apple', 100), ('banana', 50)))
print(d2, type(d2)) 
 
d2 = dict((['apple', 100], ['banana', 50]))
print(d2, type(d2))


zip
keys = {'apple', 'banana'}
values = {100, 50}
d3 = dict(zip(keys, values))
print(d3, type(d3)) # {'banana': 50, 'apple': 100} <class 'dict'>

딕셔너리의 key로 사용할 수 있는 자료형은 거의 제한이 없다.
d4 = dict()
d4[10] = '정수 가능'
d4[True] = 'bool 가능'
d4[(1,2,3)] = '튜플 가능'
# d4[[1,2,3]] = '리스트는 불가능'      
# TypeError: unhashable type: 'list
# => key는 변경 불가능해야 하지만, list는 mutable하다.
print(d4)    # {10: '정수 가능', True: 'bool 가능', (1, 2, 3): '튜플 가능'}


요소 추가 및 value 조회
fruit = {'apple': 100, 'banana': 50}
fruit['peach'] = 60
fruit['tomato'] = 80
print(fruit) # {'tomato': 80, 'apple': 100, 'peach': 60, 'banana': 50}
print(fruit['apple'])   # 100

딕셔너리는 + 연산을 지원하지 않습니다.
즉 + 연산으로 요소를 추가할 수 없습니다.
fruit1 = {'apple': 100, 'banana': 50}
fruit2 = {'peach': 100, 'kiwi': 50}
fruit3 = fruit1 + fruit2
# unsupported operand type(s) for +: 'dict' and 'dict'
print(fruit3)



딕셔너리는 mutable 합니다.
fruit = {'apple': 100, 'banana': 50}
fruit['apple'] = 80
print(fruit)        # {'apple': 80, 'banana': 50}


함수 및 메서드
fruit = {'apple': 100, 'banana': 50}

# keys()
keys = fruit.keys()
print(keys, type(keys))         # dict_keys(['apple', 'banana']) <class 'dict_keys'>

# values()
values = fruit.values()
print(values, type(values))     # dict_values([80, 50]) <class 'dict_values'>

# items()
items = fruit.items()  # key, value 쌍을 튜플로 만들고, 튜플을 원소로 갖는 리스트가 반환된다.
print(items, type(items))   # dict_items([('apple', 80), ('banana', 50)]) <class 'dict_items'>

# get()
price = fruit.get('apple')
print(price)                    # 80

print(fruit.get('melon'))       # None  => 없는 key를 get() 할 경우 예외가 발생하지 않는다.

# print(fruit["melon"])         # Exception has occurred: KeyError  발생

print(fruit.get('melon', 100))  # 100   => 없는 key일 경우 default를 할당할 수 있다.

fruit = {'apple': 100, 'banana': 50}
fruit['peach'] = 60
fruit['tomato'] = 80
fruit['apple'] = 80

{'apple': 80, 'banana': 50, 'peach': 60, 'tomato': 80}

# pop()
value = fruit.pop('banana')     # key를 가져오면서 삭제
print(value)                    # 50
print(fruit)                    # {'apple': 80, 'peach': 60, 'tomato': 80}

# popitem()
item = fruit.popitem()          # 마지막 원소를 튜플로 가져오기
print(item)                     # ('tomato', 80)
print(fruit)                    # {'apple': 80, 'peach': 60}


update(dict) : 사전형 자료에 key:value를 추가/수정
동일한 key 가 없으면, 추가
동일한 key 가 있으면, 수정
fruit = {'apple': 100, 'banana': 50,'peach':60,'tomato':80}
fruit.update({'apple':90}) # apple키의 값을 90 을 업뎃
fruit.update({'kiwi':50}) # kiwi:50 원소 추가
print(fruit.items())
 
clear() : 사전형의 모든 요소를 삭제
fruit = {'apple': 100, 'banana': 50,'peach':60,'tomato':80}
fruit.clear()
print(fruit.items())
 
 fromkeys(iterable[, value]) : iterable의 요소를 사용하여 key를 생성하는 함수.
옵션으로 value를 사용하면 기본값 생성을 한다.
list_1 = ['apple', 'banana', 'peach', 'tomato']
dic_1 = dict.fromkeys(list_1, 1000)
print(dic_1)
 
{'apple': 1000, 'banana': 1000, 'peach': 1000, 'tomato': 1000}
 
setdefault(key[, value]) : 사전형 자료에 새로운 key:value를 추가하는 함수
옵션으로 value지정하여 값 고정
dic_1 = {'apple':1000, 'banana':2000}
dic_1.setdefault('peach', 3000)
dic_1.setdefault('peach', 4000)    # 변화 없음
print(dic_1)
 
 del
dic_1 = {'apple':1000, 'banana':2000}
del dic_1['apple']
print(dic_1)
 
활용법
      #사전과 리스트를 이용한 사용
dl={'음료':['탄산','과일','우유','물'],
    '식사':['김밥','라면','돈까스','비빔밥']}
for key in dl:    #'key'값에 대한 Value(list)값 설정
    print(dl[key])
 
#리스트와 사전을 이용한 방식
ld = [{'name':'park', 'age':25, 'blood':'B'},
      {'name':'Kim','age':27,'blood':'A' }]
for dic in ld:    #indexing값에 대한 Value(dict)값 설정
    print(dic['name'], dic['age'],dic['blood']) 
 
#사전에 사전을 이용한 방식
dd = {'park':{'age':25,'blood':'B'},
      'Kim':{'age':37,'blood':'A'}}
for name in dd:   #'key'값에 대한 Value(dict)값 설정
    print(name,dd[name]['age'],dd[name]['blood']) 
 
fruit = {'apple': 100, 'banana': 50,'peach':60,'tomato':80}
for key, value in fruit.items(): #unpacking
   print(f'{key}:{value}')
결과값
apple:100
banana:50
peach:60
tomato:80
 
 
 
 
 
N차 사전(2차 사전)
    4.1 fruit 딕셔너리에서 하나의 요소를 추출하면 기본값이 key이다.
fruit = {'apple': 100, 'banana': 50,'peach':60,'tomato':80}
for key in fruit:
    print(key)
 
결과 값
apple
banana
peach
tomato

 
    4.2 fuite.items()에서 key와 values를 동시 unpacking
fruit = {'apple': 100, 'banana': 50,'peach':60,'tomato':80}
for key,val in fruit.items():
    print(key,val)
 
결과 값
apple 100
banana 50
peach 60
tomato 80

 
    4.3 fuite.items()에서 key를 unpacking하면 tuple (key,value)출력
fruit = {'apple': 100, 'banana': 50,'peach':60,'tomato':80}
for key in fruit.items():
    print(key)
 
결과 값
('apple', 100)
('banana', 50)
('peach', 60)
('tomato', 80)

 
 
2차 딕셔너리에서 value값 추출하기
dic_1 = {
    'python':{'version':3.6, 'author':'user1'},
    'java':{'version':8, 'author':'user2'},
    'c++':{'version':2.5, 'author':'user3'}
}
for key1 in dic_1:
    for key2 in dic_1[key1]:
        print(dic_1[key1][key2], end='\t')
    print()

 

lambda

인스턴트하게 일회용으로 쓰고 버리는 함수용도

# "lambda" 는 런타임에 생성해서 사용할 수 있는 익명 함수 입니다.
# 임시적 함수

def hap(a,b):
  return a + b
hap(10, 20)

(lambda x,y: x + y)(10, 20)

lam = lambda x: x**2
print(lam(8))

lam2 = lambda x,y : x+y
print(lam2(3,5))

 

 

 

 

'Python' 카테고리의 다른 글

코딩은 순서가 중요하다  (1) 2023.06.26
반복문 연습  (0) 2023.01.16
if문 심리테스트로 포켓몬 정해주는 코딩  (0) 2023.01.13
string, 내장함수, random 명령어 연습  (1) 2023.01.13
변수 문제 풀이  (0) 2023.01.12