basic_list.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
def define_list():
    """
    리스트 정의 예제
    리스트 : 순차형, Mutable, Container
    :return:
    """
 
    list1 = list()
    print(list1, type(list1))
    list2 = [1"Python", True, [123]]
    print(list2, type(list2))
 
 
 
def list_oper():
    """
    리스트 연산
    :return:
    """
 
    lst = [1"Python", True]
    print("Len:"len(lst))
    print(lst[0], lst[1], lst[2])
    print(lst[-1], lst[-2], lst[-3])
 
    print("list[1:3] : ", lst[1:3]) # 항상 끝 경계에 유의
    print("lst[1:] : ", lst[1:])
    print("lst[:3] : ", lst[:3])
    print("lst[:] : ", lst[:])
 
 
    # 단순 카피
    copy = lst[:]
    print("COPY:", copy)
    print("copy is lst?", copy is lst)
 
    # 연결
    print(lst+ ["Java", False, 3.141592])
    print("lst : ", lst)
 
 
    # oppend, extend
    copy.append(["Java", False, 3.141592])
    print("append : ", copy)
    copy = lst[:]
    copy.extend(["Java", False, 3.141592])
    print("Extend : ", copy)
 
 
    # insert : 삽입
    copy.insert(2,[123])
    print("insert : ", copy)
 
    # in, not in : 포함 여부
    print("IN:""Python" in copy)
 
    # index : 특정 항목의 인덱스 반환
    print("INDEX:"copy.index("Python"))
 
    if "Linux" in copy:
        print(copy.index("Linux"))
        print(copy)
    else:
        print("Not Found")
 
 
    # 삭제
    print("copy:", copy)
    del copy[2]
    print("copy:", copy)
 
    # 변경 가능 시퀀스
 
 
    #슬라이싱
    lst = [112123123412345]
    print("lst:", lst, type(lst))
 
 
    copy = lst[:]
    # 슬라이싱을 이용한 삽입
    print("ORGINAL:", copy)
    copy[2:2= [4564567]
    print("RESULT:", copy)
 
 
    #삭제
    # 아래 코드는 주의 : 뒤부터 지우세요
    #del copy[2]
    #del copy[3]
 
    copy[2:4= [] # 슬라이싱을 이용한 삭제
    print("RESULT:", copy)
 
    # 슬라이싱을 이용한 치환
 
    copy[2:4= ["Python""Linux""C"]
    print("RESULT : ", copy)
 
 
 
def sort_method():
    """
    sort ex
    :return:
    """
 
    lst = [102229823412]
    print("원본:", lst)
    lst.reverse() # 순서 뒤집기
    print("reverse():", lst)
 
    copy=lst.copy()
    print("copy:",copy)
    print("SORTED 함수:",sorted(copy)) #sorted함수는 원본 변경 x
    print("copy:",copy)
    print("SORTED DESC:", sorted(copy,reverse=True))
    print("SORTED key str:",sorted(copy,key=str))
 
    #key 함수의 정의
 
    def key_func(val):
        return val % 3
 
 
    print("SORTED custom key func:", sorted(copy,key=key_func))
 
 
 
def stack_ex():
 
    stack = []
    stack.append(40)
    stack.append(30)
    stack.append(20)
    stack.append(10)
    print("STACK:", stack)
 
    stack.pop()
    print("STACK:", stack)
 
    print(stack.pop())
    print(stack.pop())
    print(stack.pop())
 
    if len(stack)>0:
        print("STACK:", stack)
    else:
        print("Empty")
 
 
def queue_ex():
    """리스트를 활용한 Queue 구조
    """
 
    queue = [12]
    queue.append(3)
    queue.append(4)
    queue.append(5)
    print("QUEUE:",queue)
 
    print(queue.pop(0))
    print(queue.pop(0))
    print(queue.pop(0))
    print(queue.pop(0))
    print(queue.pop(0))
 
    if len(queue):
        print(queue.pop(0))
    else:
        print("Empty")
 
 
def loop():
    """
    리스트 순회 예제
    :return:
    """
 
    # words 안의 단어를 모두 소문자로 바꿔 리스트로 변경
    words = "Life is too short, You need to Python".lower().split()
    print(words)
 
 
 
 
 
if __name__ == "__main__":
    #define_list()
    #list_oper()
    #sort_method()
    #stack_ex()
    #queue_ex()
    loop()
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

 

 

basic_tuple.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
def define_tuple():
    """
    튜플 생성 예제
    :return:
    """
 
    t=tuple() #공튜플
    t=() # 공튜플
 
    #print(type(t))
 
    #타 순차 객체를 이용해서 생성
    t=tuple([1,2,3,4])
 
    # 순차 자료형, imutable
    # 인덱스 접근, 슬라이싱, in, not in
    print(t[-1], t[0],t[1]) # 인덱스 접근
    # t[0] = 10 #치환 불가
 
    #t=()
    t=(1,) # 요소가 하나인 튜플 작성시, 반드시 마지막에
    print(t)
    print(type((1)),type((1,)))
 
 
def tuple_methods():
    """튜플의 메서드"""
 
    t=[10,20,30,40,20]
    print(t.index(20))
    print(t.index(20,2))
    print(t.count(20))
 
 
 
def packing_unpacking():
    """
    튜플의 패킹과 언패킹
    :return:
    """
 
    t= 10,20,30,"Python" #packing
    print(t,type(t))
 
    a,b,c,d=t
    print("Unpacking", a,b,c,d)
    a, *= t # 앞에서 한 개를 언패킹 ->a,
    print(a,b)
 
    a, *b, c = t
    print(a, b, c)
 
 
 
 
 
if __name__ == "__main__":
    #define_tuple()
    #tuple_methods()
    packing_unpacking()
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

 

basic_dict.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
def define_dict():
    """
    사전정의
    :return:
    """
 
    dct=dict()
    print(dct,type(dct))
 
    # Literal을 이용한 정의
    dct={"basketball":5,"baseball":9}
 
    # key 값을 이용한 접근
    # index, 슬라이싱, 연결, 반복 불가
    # len, in, not in (key) 가능
 
    dct['volleyball']=6
    print(dct)
 
 
    # 키워드 인자값을 이용한 생성
    d1 = dict(one=1,two=2)
    print("키워드 인자 생성:",d1)
 
    # 튜플의 리스트를 이용한 생성
    d2 = dict([('k1',1),("k2",2),("k3",3)])
    #print(d2,type(d2))
 
    print(dct.keys())
    print(dct.values())
    print(dct.items()) # key, value 쌍 튜플의 목록
 
    print("basketball" in dct)
    print(9 in dct)
 
    print(9 in dct.values())
 
    #zip 객체를 이용한 생성
 
    keys = ['one''two''three']
    values= [123]
 
    print("ZIP:",zip(keys,values))
    d2 = dict(zip(keys, values))
    print(d2)
 
 
def using_dict():
    """
    사전 사용법
    :return:
    """
 
    phones = {"홍길동":"010-1234-5678",
              "장길산":"010-1111-2222",
              "전우치":"010-7766-2211"}
 
    print("phones keys : "phones.keys())
    print(phones, type(phones))
 
    phones['임꺽정']="010-9999-9999"
    print(phones)
 
    #print(phones['둘리']) #키가 없으면 오류
    print(phones.get("둘리")) #키가 없으면 None
    print(phones.get("둘리","누구?"))
 
    # 삭제 del
    del phones['장길산']
    print(phones)
 
    # 키 값이 없을 때의 삭제
    if '둘리' in phones:
        del phones['둘리']
    else:
        print("없습니다.")
 
    # pop, popitem
    data = phones.pop('홍길동')
    print(data)
    print(phones)
 
 
def loop():
    """
    사전의 loop
    :return:
    """
    phones = {"홍길동""010-1234-5678",
              "장길산""010-1111-2222",
              "전우치""010-7766-2211"}
 
 
    # 기본 적인 루프
    for key in phones:
        print(key) # key 값 출력
 
    # 키, 값 쌍 튜플을 받아와서 사용
 
    for item in phones.items():
        print("KEY:",item[0], "Value:", item[1])
 
 
    # 언 패킹 이용
    for key, value in phones.items():
        print("KEY:",key, "Value:", value)
 
 
 
 
if __name__ == "__main__":
    #define_dict()
    #using_dict()
    loop()
 
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

+ Recent posts