알파카징징이 알파카징징이 코딩하는 알파카

데이터 구조 및 분석 ch_1_6 List, Tuple, Dictionary

» writing

KAIST 산업및시스템공학과 문일철_ 데이터 구조 및 분석 수업을 참고하여 작성하였습니다

ch_1_6 List, Tuple, Dictionary

정의


List, Tuple, Dictionary

1. Index in Sequence
: index applies to strings as well as tuples, lists
-> Applies to any sequence variables
strTest = "Hello World's gani"
print(strTest)
print(strTest[1], strTest[2], strTest[3])   # -> sequence, or any array
print(strTest[1:3])     # -> x:y from x to y
print(strTest[3:])
print(strTest[:3])
print(strTest[1:9:2])   # -> x:y:z from x to y with z steps
print(strTest[1:len(strTest):2])    # -> len 길이
print(strTest[1::2])
print(strTest[5::-1])   #default y = length of sequence, z = 1

# Hello World's gani
# e l l
# el
# lo World's gani
# Hel
# el o
# el ol' ai
# el ol' ai
#  olleH
2. List
: list is another type of sequence variables
: 무엇이든 다 저장된다
lstTest = [1, 2, 3, 4]
print(lstTest)
print(lstTest[0], lstTest[1], lstTest[2])
print(lstTest[-1], lstTest[-2])
print(lstTest[1:3])
print(lstTest + lstTest)        # -> how the operator work
print(lstTest*3)

lstTest = list(range(1, 20, 3))     # -> range(x,y,z) == x:y:z
print(lstTest)
print( 4 in lstTest, 100 in lstTest)    # in and not in comes pretty handy
lstTest.append('hey')
del lstTest[0]
print(lstTest)
lstTest.reverse()
print(lstTest)
lstTest.remove(4)
print(lstTest)
lstTest.sort()
print(lstTest)

# [1, 2, 3, 4]
# 1 2 3
# 4 3
# [2, 3]
# [1, 2, 3, 4, 1, 2, 3, 4]
# [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
# [1, 4, 7, 10, 13, 16, 19]
# True False
# [4, 7, 10, 13, 16, 19, 'hey']
# ['hey', 19, 16, 13, 10, 7, 4]
# ['hey', 19, 16, 13, 10, 7]
3. Tuple
: tuple and list are almost alike
: only different in changing values
(tuple does not allow value changes)
tplTest = (1, 2, 3)
print(tplTest)
print(tplTest[0], tplTest[1], tplTest[2])
print(tplTest[-1], tplTest[-2])
print(tplTest[1:3])
print(tplTest + tplTest)
print(tplTest * 3)
tplTest[0] = 300

# (1, 2, 3)
# 1 2 3
# 3 2
# (2, 3)
# (1, 2, 3, 1, 2, 3)
# (1, 2, 3, 1, 2, 3, 1, 2, 3)
# Traceback (most recent call last):
#   File "C:/Users/82106/PycharmProjects/계산기/main.py", line 43, in <module>
#     tplTest[0] = 300
# TypeError: 'tuple' object does not support item assignment
4. Dictionary
: dictionary is also a collection variable type
: It is not sequential (선형적 X)(연속적 X)
: works by a pair of keys and values
: set of (key1, value1)
: Exact syntax {key1:value1}
dicTest = {1:'one', 2:'two',3 : 'three'}
print(dicTest[1])
dicTest[4] = 'four'     # -> 4: 'four'
print(dicTest)
dicTest[1] = 'hana'
print(dicTest)
print(dicTest.keys())
print(dicTest.values())
print(dicTest.items())      # (1, hana) like list

# one
# {1: 'one', 2: 'two', 3: 'three', 4: 'four'}
# {1: 'hana', 2: 'two', 3: 'three', 4: 'four'}
# dict_keys([1, 2, 3, 4])
# dict_values(['hana', 'two', 'three', 'four'])
# dict_items([(1, 'hana'), (2, 'two'), (3, 'three'), (4, 'four')])