20230308 KDT 수업일지

2023. 3. 9. 14:01학습일지

728x90

1-5. enumerate

  • 반복문 사용 시 몇번째 반복인지 인덱스 번호로 확인
  • 인덱스 번호와 요소를 튜플 형태로 변환
li1 = [1020304050]
for e in enumerate(li1):
    print(e)
(0, 10)
    (1, 20)
    (2, 30)
    (3, 40)
    (4, 50)
for i, v in enumerate(li1):
  print(f'index:{i}, value:{v}')
index:0, value:10
index:1, value:20
index:2, value:30
index:3, value:40
index:4, value:50

1-6. zip() 함수

  • 객체가 담고 있는 원소를 엮어서 튜플의 형태로 반환
  • 매개변수의 길이기 다를 때는 짧은 매개변수 기준으로 데이터가 엮이고, 나머지는 버려짐
li1 = [10,20,30]
li2 = ['apple','banana','orange']

for i in range(len(li1)):
  print((li1[i],li2[i]))

(10, 'apple')

   (20, 'banana')

   (30, 'orange')

for n, A, a in zip('12345','ABCDE','abcde'):
  print((n,A,a))

- ('1', 'A', 'a')

   ('2', 'B', 'b')

   ('3', 'C', 'c')

   ('4', 'D', 'd')

   ('5', 'E', 'e')

1-6 list와 tuple을 for문과 함께 사용하기

li1 = ['apple''banana''orange''melon']

for i in li1:
  print(i,end=' ')
 
- apple banana orange melon
 

문제

아래 score 리스트에 저장된 점수가 60점 이상인 학생이 몇명인지 알아보는 프로그램을 작성해보자

score = [90,30,50,60,80,70,100,40,20,10]

 

sco = [90,30,50,60,80,70,100,40,20,10]
count = 0
 
for i in sco:
  if i >= 60:
    count += 1
print(f' 60점이상인 학생의 수는 {count}명입니다.')
- 60점이상인 학생의 수는 5명입니다.
 

2. 다중반복문

  • 반복문이 2개이상 겹쳐져 있는 형태
for i in range(1,4):
  print(f'😎i:{i}')
  for j in range(1,4):
    print(f'   😋j:{j}')

-

😎i:1

     😋j:1

     😋j:2

     😋j:3

😎i:2

     😋j:1

     😋j:2

     😋j:3

😎i:3

     😋j:1

     😋j:2

     😋j:3

#: '🤑'를 이용하여  아래와 같은 도형을 만들어보자
for i in range(5):
  for j in range(5):
    print('🤑',end=' ')
  print()

🤑 🤑 🤑 🤑 🤑

🤑 🤑 🤑 🤑 🤑

🤑 🤑 🤑 🤑 🤑

🤑 🤑 🤑 🤑 🤑

🤑 🤑 🤑 🤑 🤑

문제

'🤑'를 이용하여 아래와같은 도형을 만들어보자.
🤑🤑🤑🤑🤑
🤑🤑🤑🤑
🤑🤑🤑
🤑🤑
🤑
 
for i in range(5):
  for j in range(i,5):
    print('🤑',end=' ')
  print()
 -
🤑🤑🤑🤑🤑
🤑🤑🤑🤑
🤑🤑🤑
🤑🤑
🤑

문제 2

'🤑'를 이용해서 아래와 같은 도형을 만들어보자

🤑
🤑🤑
🤑🤑🤑
🤑🤑🤑🤑
🤑🤑🤑🤑🤑
 
for i in range(5):
  for j in range(0,i+1):
    print('🤑',end=' ')
  print()

-

🤑

🤑 🤑

🤑 🤑 🤑

🤑 🤑 🤑 🤑

🤑 🤑 🤑 🤑 🤑

 

2단부터 9단까지 구구단을 출력하는 프로그램을 작성

2단 2*1=2 2*2=4 ..

3단

..

9단

for i in range(2,10):
  print(f'{i}단')

  for j in range(1,10):

    print(f'{i} * {j} = {i*j}')
-
2단
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
3단
3 * 1 = 3
3 * 2 = 6
3 * 3 = 9
3 * 4 = 12
3 * 5 = 15
3 * 6 = 18
3 * 7 = 21
3 * 8 = 24
3 * 9 = 27
4단
4 * 1 = 4
4 * 2 = 8
4 * 3 = 12
4 * 4 = 16
4 * 5 = 20
4 * 6 = 24
4 * 7 = 28
4 * 8 = 32
4 * 9 = 36
5단
5 * 1 = 5 
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
6단
6 * 1 = 6
6 * 2 = 12
6 * 3 = 18
6 * 4 = 24
6 * 5 = 30
6 * 6 = 36
6 * 7 = 42
6 * 8 = 48
6 * 9 = 54
7단
7 * 1 = 7
7 * 2 = 14
7 * 3 = 21
7 * 4 = 28
7 * 5 = 35
7 * 6 = 42
7 * 7 = 49
7 * 8 = 56
7 * 9 = 63
8단
8 * 1 = 8
8 * 2 = 16
8 * 3 = 24
8 * 4 = 32
8 * 5 = 40
8 * 6 = 48
8 * 7 = 56
8 * 8 = 64
8 * 9 = 72
9단
9 * 1 = 9
9 * 2 = 18
9 * 3 = 27
9 * 4 = 36
9 * 5 = 45
9 * 6 = 54
9 * 7 = 63
9 * 8 = 72
9 * 9 = 81

문제

 

*아래 score 리스트의 요소를 모두 출력하는 프로그램을 작성해보자

  • score =[[80,90,50],[40,70,30],[90,50,100]]
score =[[80,90,50],[40,70,30],[90,50,100]]

 

for i in range(3):
    # print(score[i])
     for j in range(3):
       print (score[i][j],end=' ')
 
- 80 90 50 40 70 30 90 50 100
for i in score:
  for j in i:
    print(j, end=' ')

 

- 80 90 50 40 70 30 90 50 100

3.컴프리헨션(comprehansion)

  • 이터러블한 오브젝트를 생성하기 위한 방법 중 하나로 파이썬에서 사용할 수 있는 유용한 기능
n = range(0101)
print(n)
- range(0, 10)
n = 10

result = [0 for i in range(n)]
print(result)
- [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
result = [i for i in range(n)]
print(result)
- [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 
arr = [0,1,2,3,4,5,6,7,8,9]

result = [n for n in arr]
print(result)
- [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 
arr = ['apple','banana','orange','melon']

result = [len(string) for string in arr]
print(result)
- [5, 6, 6, 5]
result = [n for n in range(10)if n^2 == 0]
print(result)
- []
 
arr = [-10-4245-102]

#양수는 리스트에 그대로 저장하고, 음수는 0으로 변환해서 저장하기
result = [n if n>0 else 0 for n in arr]
print(result)
- [0, 0, 0, 24, 5, 0, 2]
 
arr = []

for i in range(1,4):
  for i in range(1,3):
    arr.append(i*j)

print(arr)

- [1, 2, 1, 2, 1, 2]

arr = [i*j for i in range(1,4for j in range(1,3)]
print (arr)
- [1, 2, 2, 4, 3, 6]
 
result = [[0 for i in range(2)] for j in range(3)]
print(result)

- [[0, 0], [0, 0], [0, 0]]

-----------------------------------------------------------------------------------------------------------------------------------------------------------------

1. 딕셔너리(Dictionary)

  • 대응관계를 나타내는 자료형으로 key와 value라는 것을 한 쌍으로 갖는 형태
  • 하나의 딕셔너리의 key는 중복될 수 없음
  • 하나의 딕셔너리의 value는 중복될 수 없음

1-1 딕셔너리 만들기

변수 = {키: 값1, 키2: 값,,,)

dic1 = {} #빈 딕셔너리를 생성
print(dic1)
- {}
 
dic2 = {1:'김사과',2:'반하나',3:'오렌지',4:'이메론'}
print(dic2)
- {1: '김사과', 2: '반하나', 3: '오렌지', 4: '이메론'}
 

1-2. key를 통해 value찾기

dic2 = {1:'김사과',2:'반하나',3:'오렌지',4:'이메론'}
print(dic2[1])
print(dic2[3])
- 김사과
  오렌지
 
dic3 = {'no':1'userid ':'apple','name':'김사과''hp':'010-1111-1111'}
print(dic3['no'])
print(dic3['user id'])
 
KeyError                                  Traceback (most recent call last)
<ipython-input-18-98571a1aef30> in <module>
      1 dic3 = {'no':1, 'userid ':'apple','name':'김사과', 'hp':'010-1111-1111'}
      2 print(dic3['no'])
----> 3 print(dic3['user id'])

KeyError: 'user id'
1

1-3. 데이터 추가 및 삭제

dic4 = {1:'apple'}
print(dic4)

dic4[100] ='orange'
print(dic4)

dic4[50] = 'melon'
print(type(dic4))

del dic4[1]
print(dic4)

print(type(dic4))

 

- {1: 'apple'}

  {1: 'apple', 100: 'orange'}

   <class 'dict'>

  {100: 'orange', 50: 'melon'}

   <class 'dict'>

1-4딕셔너리 함수

dic3 = {'no':1'userid':'apple','name':'김사과''hp':'010-1111-1111'}
 
#key() :key 리스트를 반환
print(dic3.keys())
 
dict_keys(['no', 'user id ', 'name', 'hp'])
 
#values() : value 리스트를 반환
print(dic3.values())
- dict_values([1, 'apple', '김사과', '010-1111-1111'])
 
#items():keyd와 value를 한 쌍으로 묶는 튜플을 반환
print(dic3.items())

- dict_items([('no', 1), ('user id ', 'apple'), ('name', '김사과'), ('hp', '010-1111-1111')])

 

print(dic3['userid'])


#get(): key를 이용해서 value를 반환
print(dic3.get('userid'))
- apple
  apple
 
print(dic3['age'])#키가 존재하지 않으면 에러
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-40-18786cb7081a> in <module>
----> 1 print(dic3['age'])#키가 존재하지 않으면 에러

KeyError: 'age'
print(dic3.get('age')) #None
print(dic3.get('age','나이를 알 수 없음'))
- None
  나이를 알 수 없음
 
# in : key가 딕셔너리 안에 있는지 확인
print('name'in dic3) #True
print('age' in dic3) #False
- True
  False
 

1-5 반복문을 이용한 딕셔너리 활용

dic3 = {'no':1'userid':'apple''name':'김사과','hp':'010-1111-1111'}
 
for i in dic3:
  print(i, end=' ')#키만 복사
- no userid name hp
 
for i in dic3.keys():
  print(i, end=' ')#키만 복사
- no userid name hp
 
for i in dic3.values():
  print(i,end=' ')#값만 복사
- 1 apple 김사과 010-1111-1111
 
for i in dic3:
  print(dic3[i],end=' ')
- None None None None
 
#각 키를 순회하면서 키에 해당하는 값이 'apple'이 있는지 확인
dic3 ={'no':1'userid':'apple','name':'김사과','hp':'010-1111-1111'}

for i in dic3:
  if dic3[i] =='apple':
    print('찾았습니다')
  else:
    print('찾지 못했습니다.')
- 찾지 못했습니다.
  찾았습니다
  찾지 못했습니다.
  찾지 못했습니다.
-----------------------------------------------------------------------------------------------------------------------------------------------------------------

1. 세트(set)

  • 수학의 집합과 비슷한 형태로 순서가 없어서 어떤 값이 먼저 나올지 알 수 없고, 중복되는 데이터를 허용하지 않음
  • 딕셔너리처럼 중괄호를 사용해서 선언하지만, key는 존재하지 않고 value만 존재

1-1. set만들기

s1 = {}
print(s1)
print(type(s1))
-
{}
<class 'dict'>
 
s1 = {1,3,5,7}
print(s1)
print(type(s1))
- {1, 3, 5, 7}
  <class 'set'>
 
li1 = [1,3,5,7]
s2 = set(li1)
print(s2)
- {1, 3, 5, 7}
 
s3 = {1,3,5,3,7,9,1}
print(s3)
- {1, 3, 5, 7, 9}
 
li2 = [1,3,5,3,7,9,1]
print(li2)
s4 = set(li2)
print(s4)
- [1, 3, 5, 3, 7, 9, 1]
  {1, 3, 5, 7, 9}
 
print(3 in s4)
- True
 
print(3 in s4)#True
print(8 in s4)#False
print(8 not in s4)#True
- True
  False
  True

1-2 set함수

# add(): set에 단일 데이터를 추가
s1 = {100,200}
s1.add(150)
print(s1) # 순서가 일정하지 않음
s1.add(50)
print(s1)

- {200, 100, 150}

  {200, 50, 100, 150}

 

#update(): set에 여러 데이터를 한번에 추가
s2 = {10,20,30}
s2.update([40,50,60,20])
print(s2)
- {40, 10, 50, 20, 60, 30}
 
#remove(): set의 데이터를 제거, 제거할 데이터가 없으면 에러
s2.remove(50)
print(s2)

- {40, 10, 20, 60, 30}

s2.remove(50#KeyError
 
print(s2)
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-12-8ad4064136d0> in <module>
----> 1 s2.remove(50)
      2 print(s2)

KeyError: 50
#discard(): set의  데이터를 제거, 제거할 데이터가 없어도 에러가 발생하지 않음
s2.discard(30)
print(s2)
- {40, 10, 20, 60}
#copy(): set을 복사
#id(): 저장된 메모리 주소를 10진수로 표현
s3 = {10,20,30}
s4 = s3.copy()
print(s3)
print(s4)
print(id(s3))
print(id(s4))
- {10, 20, 30}
  {10, 20, 30}
li1 = [1,2,3,4]
li2 = li1
print(id(li1))
print(id(li2))
- 140399300904256
  140399300904256

1-3 set의 연산자

-

s1 = {10,20,30,40,50}
s2 = {30,40,50,60,70}
 
# 합집합
result = s1  | s2
print(result)
result = s1.union(s2)
print(result)

- {70, 40, 10, 50, 20, 60, 30}

  {70, 40, 10, 50, 20, 60, 30}

 

# 교집합
result = s1 & s2
print(result)
result = s1.intersection(s2)
print(result)
- {40, 50, 30}
  {40, 50, 30}

 

#차집합
result = s1 - s2
print(result)
result(s1,difference(s2))
print(result)
-
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-45-5f32916f4f5c> in <module>
      2 result = s1 - s2
      3 print(result)
----> 4 result(s1,difference(s2))
      5 print(result)

NameError: name 'difference' is not defined
{10, 20}
#대칭 차집합
result = s1^ s2
print(result)
result = s1.symmetric_difference(s2)
print(result)
- {20, 70, 10, 60}
  {20, 70, 10, 60}

2. 세트와 zip()함수

{20, 70, 10, 60}
{20, 70, 10, 60}
코드텍스트
{20, 70, 10, 60}
{20, 70, 10, 60}
string = 'apple'
li = [1,2,3,4,5]
tu = ('김사과','반하나','오렌지','이메론','채애리')
 
print(zip(string,li,tu))
- <zip object at 0x7fb15a7b52c0>
 
print(list(zip(string,li,tu)))
- [('a', 1, '김사과'), ('p', 2, '반하나'), ('p', 3, '오렌지'), ('l', 4, '이메론'), ('e', 5, '채애리')]
 
print(set(zip(string,li,tu)))
- {('a', 1, '김사과'), ('p', 2, '반하나'), ('e', 5, '채애리'), ('p', 3, '오렌지'), ('l', 4, '이메론')}
 
print(dict(zip(li,tu)))
- {1: '김사과', 2: '반하나', 3: '오렌지', 4: '이메론,채애리'}
-----------------------------------------------------------------------------------------------------------------------------------------------------------------

 

 

 

728x90
반응형

'학습일지' 카테고리의 다른 글

20230310 KDT 학습일지  (0) 2023.03.10
20230309 KDT 학습일지  (0) 2023.03.10
20230307 KDT 학습일지  (0) 2023.03.07
20230306 KDT 수업일지  (0) 2023.03.06
20230303 KDT 수업일지  (0) 2023.03.03