본문으로 바로가기

1. for문

# 유용한 기능

1. enumerate()

- enumerate(iterable, start=0)

- '누적시키다'라는 뜻으로, iterable 객체를 추출할 때 함께 index를 하나씩 늘려 추출하는 함수

for idx, name in enumerate(students, start=1):
	print('오늘 {}위는 {}입니다.'.format(idx, name))
    
    
# enumerate 기능을 사용하지 않는다면:
idx = 1
for name in students:
    print('오늘 {}위는 {}입니다.'.format(idx, name))
    idx += 1

 

2. zip()

- zip(self, /, *args, **kwargs)

- 여러 개의 iterable 객체들을 인자(parameter)로 받고, 각 객체에서 원소 하나씩 추출하여 tuple의 형태로 묶어주는 함수

purchase_info = []
for item, ord_num in zip(items, order_numbers):
    purchase = {item: ord_num}
    puchase_info.append(purchase)

 

3. tqdm()

- 반복문 진행상황을 파악하는 방법 (진행표시바 보여줌)

- 라이브러리를 설치해야 한다

- 주로 규모가 큰 데이터를 사용할 때 자주 사용된다

#!pip install tqdm
import time
from tqdm import tqdm

for i in tqdm(range(len(parm1)):
    for j in tqdm(range(len(parm2)):
    	print(???)
        time.sleep(0.1)

예시 사진 (https://www.tensorflow.org/addons/tutorials/tqdm_progress_bar?hl=ko)

 


# 유용한 함수

1. Counter

- 항목의 개수를 셀 때 사용하는 함수

from collections import Counter

sentence = 'This is the sample sentence. Sentence is comprised with words. Word is a group of charactors. NLP is short for Natural Language Programming. It covers the topics related with real words & sentences in language'
words = sentence.lower().split(' ')
# Counter() type은 collections.Counter이므로 마지막에 dict type으로 바꿔주기
bag_of_words = dict(Counter(words))   
print(bag_of_words)


# Counter 함수를 사용하지 않는다면:
bag_of_words = {}
for word in words:
    if word not in bag_of_words:
        bag_of_words[word] = 1
    else:
        bag_of_words[word] += 1
print(bag_of_words)

 

 


2. while문

- pass와 continue의 차이점

while True:	
    pass	# 실행할 코드가 없으니 다음 행동을 계속해서 진행해라
    continue	# 바로 다음 loop로 돌아가라