python 잘쓰자

정지원·2020년 7월 1일
0

본 포스팅은 프로그래머스의 '파이썬을 파이썬답게' 강의를 정리한 것입니다

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

🔥int(x:string, base = 10)
int('31',5) # 16

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

s = '가나다라'
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

2차원 리스트 뒤집기 - zip

col과 row 바꾸기

mylist = [ [1,2,3], [4,5,6], [7,8,9] ]
🔥new_list = list(map(list, zip(*mylist)))
# [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

여러 개의 리스트 한번에 순회하기

a = [1,2,3]
b = [4,5,6]
🔥for tuple_ in zip(a,b):
    print(tuple_)
# (1, 4)
# (2, 5)
# (3, 6)

응용 - 리스트 두 개를 딕셔너리 형태로 가공
두 리스트가 각각 key와 value를 담당한다.

keys = ['a','b','c']
values = [1,2,3]
my_dict = dict(zip(keys, values)) # {'a': 1, 'b': 2, 'c': 3}

map

map(function_object, iterable1, iterable2,...)

a, b = map(len, [[1],[1,2]]) # a: 1, b: 2

# 여러 iterable를 활용할 수 있다.
l1 = [1, 2, 3, 4]
l2 = [10, 20, 30, 40]
list(map(lambda x, y: x+y, l1, l2)) # [11, 22, 33, 44]

itertools

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

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

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

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

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

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

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

0~100 사이의 짝수 구하기

  • count : count(시작, [step]) 의 함수로 시작 숫자부터 step만큼(없으면 1) 씩 무한히 증가하는 제네레이터입니다.
  • islice : islice(iterable객체, [시작], 정지[,step])의 함수로, iterable한 객체를 특정 범위로 슬라이싱하고 iterator로 반환됩니다.
itertools.islice((x for x in itertools.count(1) if x%2 == 0),100)

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

import collections

a = collections.Counter('abcdaaab')
# Counter({'a': 4, 'b': 2, 'c': 1, 'd': 1})

a.most_common([n])
# [('a', 4), ('b', 2), ('c', 1), ('d', 1)]

for-else

for i in range(5):
    if i > 5:
        print("there is bigger than 5")
else:
    print("all of them are smaller than 5")
# all of them are smaller than 5

swap

a,b = b,a
import bisect
mylist = [1, 2, 3, 7, 9, 11, 33]
print(bisect.bisect(mylist, 3)) # 3
  • bisect.bisect(list, x, lo=0, hi=len(a))
    bisect()는 list라는 오름차순으로 정렬된 시퀀스에 x값이 들어갈 위치를 리턴한다.
  • bisect.insort(list, x, lo=0, hi=len(a))
    insort()는 list라는 오름차순으로 정렬된 시퀀스에 x값을 삽입한다.

무한대 - inf

float('inf') # 어떤 수랑 비교하더라도 무조건 크다
float('-inf') # 어떤 수랑 비교하더라도 무조건 작다
  • map
  • join
  • * 연산

0개의 댓글