파이썬을 파이썬답게
Dev

파이썬을 파이썬답게

출처: programmers.co.kr

몫과 나머지 - divmod

a = 7
b = 5
print(*divmod(a, b))

 

n진법으로 표기된 string을 10진법 숫자로 변환하기 - int 함수

파이썬의 int(x, base = 10) 함수는 진법 변환을 지원함

num = '3212'
base = 5
answer = int(num, base)

 

문자열 정렬하기 - ljust, center, rjust

s = 'JOFT'
n = 7

s.ljust(n) # 좌측 정렬
s.center(n) # 가운데 정렬
s.rjust(n) # 우측 정렬

 

알파벳 출력하기 - string 모듈

import string 

string.ascii_lowercase # 소문자 abcdefghijklmnopqrstuvwxyz
string.ascii_uppercase # 대문자 ABCDEFGHIJKLMNOPQRSTUVWXYZ
string.ascii_letters #대소문자 모두 abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
string.digits # 숫자 0123456789

 

원본을 유지한채, 정렬된 리스트 구하기 - sorted

반복문이나, deepcopy 함수를 사용하지 않아도 새로운 정렬된 리스트를 구할 수 있다.

list1 = [3, 2, 1]
list2 = sorted(list1)

 

2차원 리스트 뒤집기 - zip

'zip' returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables.

mylist = [1, 2, 3]
new_list = [40, 50, 60]
for i in zip(mylist, new_list):
    print (i)

(1, 40)
(2, 50)
(3, 60)
list1 = [1, 2, 3, 4]
list2 = [100, 120, 30, 300]
list3 = [392, 2, 33, 1]
answer = []
for i, j, k in zip(list1, list2, list3):
   print(i + j + k)
animals = ['cat', 'dog', 'lion']
sounds = ['meow', 'woof', 'roar']
answer = dict(zip(animals, sounds)) # {'cat': 'meow', 'dog': 'woof', 'lion': 'roar'}

 

i번째 원소와 i+1번째 원소 - zip

파이썬의 zip을 이용하면 index를 사용하지 않고 각 원소에 접근할 수 있다.

def solution(mylist):
    answer = []
    for number1, number2 in zip(mylist, mylist[1:]):
        answer.append(abs(number1 - number2))
    return answer

 

모든 멤버의 type 변환하기 - map

파이썬의 map을 사용하면 for 문을 사용하지 않고도 멤버의 타입을 일괄 변환할 수 있다.

list1 = ['1', '100', '33']
list2 = list(map(int, list1))

 

sequence 멤버를 하나로 이어붙이기 - join

시퀀스의 멤버들을 하나의 string으로 이어붙여야 할 때 사용

my_list = ['1', '100', '33']
answer = ''.join(my_list)
#110033

 

삼각형 별찍기 - sequence type의 * 연산

곱셈 연산 *를 통해 문자열을 반복하는 방법

n = 3
answer = 'abc'*n
#abcabcabc
n = 3
answer= [123, 456]*n
#[123,456,123,456,123,456]

 

곱집합(Cartesian product) 구하기 - product

iterable으로 곱집합을 구하는 방법

import itertools

iterable1 = 'ABCD'
iterable2 = 'xy'
iterable3 = '1234'
itertools.product(iterable1, iterable2, iterable3)

 

2차원 리스트를 1차원 리스트로 만들기 - from_iterable

my_list = [[1, 2], [3, 4], [5, 6]]

# 방법 1 - sum 함수
answer = sum(my_list, [])

# 방법 2 - itertools.chain
import itertools
list(itertools.chain.from_iterable(my_list))

# 방법 3 - itertools와 unpacking
import itertools
list(itertools.chain(*my_list))

# 방법 4 - list comprehension 이용
[element for array in my_list for element in array]

# 방법 5 - reduce 함수 이용 1
from functools import reduce
list(reduce(lambda x, y: x+y, my_list))

# 방법 6 - reduce 함수 이용 2
from functools import reduce
import operator
list(reduce(operator.add, my_list))

 

순열과 조합 - combinations, permutations

itertools.permutation를 이용하면, for문을 사용하지 않고도 순열을 구할 수 있다.

조합은 itertools.combinations를 사용해서 구할 수 있다.

import itertools

pool = ['A', 'B', 'C']
print(list(map(''.join, itertools.permutations(pool)))) # 3개의 원소로 수열 만들기
print(list(map(''.join, itertools.permutations(pool, 2)))) # 2개의 원소로 수열 만들기

 

가장 많이 등장하는 알파벳 찾기 - Counter

 어떤 원소 x가 주어진 시퀀스타입에 몇 번이나 등장하는지 세야 할 때

import collections 
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 7, 9, 1, 2, 3, 3, 5, 2, 6, 8, 9, 0, 1, 1, 4, 7, 0]
answer = collections.Counter(my_list) 
print(answer[1]) # = 4 
print(answer[3]) # = 3 
print(answer[100]) # = 0

 

for 문과 if문을 한번에 - List comprehension의 if 문

파이썬의 list comprehension을 사용하면 한 줄 안에 for 문과 if 문을 한 번에 처리할 수 있다.

mylist = [3, 2, 6, 7] 
answer = [i**2 for i in mylist if i %2 == 0]

 

for - else문

for ~ else문은 “for문에서 break가 발생하지 않았을 경우”의 동작을 else문에 적어주는 것이다.

import math 
numbers = [int(input()) for _ in range(5)] 
multiplied = 1 
for number in numbers: 
	multiplied *= number 
    if math.sqrt(multiplied) == int(math.sqrt(multiplied)): 
    	print('found') 
        break 
        
else: print('not found')

 

SWAP

스왑 가능

a = 3
b = 4

a, b = b, a

 

이진 탐색하기 - binary search

bisect.bisect 메소드를 사용하면 binary search를 간략하게 만들 수 있다.

import bisect
mylist = [1, 2, 3, 7, 9, 11, 33]
print(bisect.bisect(mylist, 3))

 

가장 큰 수 - inf

inf는 어떤 숫자와 비교해도 무조건 크다고 판정된다. 음수도 가능.

min_val = float('inf')
min_val > 10000000000
max_val = float('-inf')

 

파일 입출력

  1. 파일을 close 하지 않아도 된다: with - as 블록이 종료되면 파일이 자동으로 close
  2. readlines가 EOF까지만 읽으므로 while 문 안에서 EOF를 체크할 필요가 없다.
with open('myfile.txt') as file:
    for line in file.readlines():
        print(line.strip().split('\t'))

 

 

728x90