PYTHON

파이썬(반복문,collections)

Positive_Monster 2022. 3. 27. 19:04
더보기

▣ 주요 키워드

  1. 반복문
    • while문
      • continue, break
      • ※pop(), print(end='')옵션
    • for문
      • ※range()
  2. collections
    • defaultdict
    • Counter
    • ※get, setdefault

★ 반복문

1. while문

1. while문
- 조건이 True인 동안에 반복을 수행한다.

while 조건문:
  반복수행할 문장
i = 0
while i <= 10:
    print(i)
    i += 1

- continue, break

i = 1
while i <= 10:
    if i%2 == 1:
        print(i)
        i += 1
    else:
        if i != 10:
            i += 1
            continue # continue문을 만나면 바로 다음 반복문을 실행함
            print('실행안됨')
        else:
            print('끝')
            break # break문을 만나면 반복문을 끝내고 나오기
            print('실행안됨')

- pop() : 리스트에서 제일 마지막 인덱스에 있는 값을 추출해내기(추출하면 리스트에서 제거됨)

x = [10,25,46,78,99]
while x:
    temp = x.pop() # pop() : 리스트에서 제일 마지막 인덱스에 있는 값 뽑아내기(리스트에서는 제거됨)
    if temp >= 50:
        print('50보다 큰 {}'.format(temp))
    else:
        print('50보다 작은 {}'.format(temp))

※ print(end=' ') : end옵션은 print 할 때 한 칸 띄어서 가로로 출력하는 옵션(기본값은 end = '\n')

 

2. for문

2. for 문
리스트, 튜플, 문자열의 첫번째 값부터 마지막 값까지 순서대로 변수에 입력해서 반복수행한다.

for 변수 in (리스트, 튜플, 문자열):
  반복수행할 문장
# 문자열, 리스트, 튜플
x = '12345' # 문자열은 한 글자씩
for i in x:
    print(i)
    
y = [1,2,3,4,5]
for i in y:
    print(i)
    
z = (1,2,3,4,5)
for i in z:
    print(i)

for i in 'mypython': # 문자열은 한 글자씩
    print(i)

# 리스트안에 한 인덱스당 여러개의 값이 있을경우
x = [(1,2),(3,4),(5,6)]

for i in x:
    print(i)
    
for i,j in x: # 각인덱스마다 있는 값의 개수만큼 변수를 만들어줄 수 있음
    print(i, j)

'

※ range(시작, 끝(미만), 증가분)

list(range(1,11,1))
# 1부터 10까지 1씩 증가

 

★ collection

- collections.defaultdict(기본값설정함수(자료형, 함수 등)) : 모든 키에 대해서 값이 없는 경우 기본값 설정 함수를 넣어줌으로써 따로 기본값을 설정안 해도 됨

- collections.Counter() : 동일한 값이 몇 개인지 알 수 있는 함수

※ dict.get(키값, default) :  get(키값) -> values값 출력, 키값이 없으면 default값 출력

dict.setdefault :  키값에 대해서 기본값을 설정해주는 함수

-빈도수 체크하기 여러가지 방법
word = ('사랑','우정','인생','사랑','인생','고민','열정','열정',
        '관심','인생','취업','취업','애정','애정','열정','사랑')
        
1. 기본
word_c = {}
for i in word:
    if i not in word_c:
        word_c[i] = 1
    else:
        word_c[i] += 1
word_c

2. setdefault
word_c = {}
for i in word:
    word_c.setdefault(i,0)
    word_c[i] += 1
word_c

3. get
word_c = {}
for i in word:
    c = word_c.get(i,0)
    word_c[i] = c + 1

4. collections.defaultdict()
word_c = collections.defaultdict(int)
for i in word:
    word_c[i] += 1
word_c

5. collections.Counter()
collections.Counter(word)