๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Language/python

python ๊ฟ€ํŒ๐Ÿฏ

 

๐Ÿฏ string์„ 10์ง„๋ฒ•์œผ๋กœ

ํŒŒ์ด์ฌ์˜ int(x, base=10) ํ•จ์ˆ˜๋Š” 10์ง„๋ฒ•์œผ๋กœ ๋ณ€ํ™˜ํ•ด์ค€๋‹ค.

num = '0001'
base = 2
answer = int(num, base)    #1

 

๐Ÿฏ ๋ฌธ์ž์—ด ์ •๋ ฌํ•˜๊ธฐ - ljust, center, rjust

๋ฌธ์ž์—ด s๋ฅผ ์ขŒ์ธก/๊ฐ€์šด๋ฐ/์šฐ์ธก ์ •๋ ฌํ•˜์—ฌ n ๊ธธ์ด์˜ ๋ฌธ์ž์—ด์„ ๋งŒ๋“ ๋‹ค.

s = '๊ฐ€๋‚˜๋‹ค๋ผ'
n = 7

s.ljust(n) # '๊ฐ€๋‚˜๋‹ค๋ผ   ' # ์ขŒ์ธก ์ •๋ ฌ
s.center(n) # '  ๊ฐ€๋‚˜๋‹ค๋ผ ' # ๊ฐ€์šด๋ฐ ์ •๋ ฌ
s.rjust(n) # '   ๊ฐ€๋‚˜๋‹ค๋ผ' # ์šฐ์ธก ์ •๋ ฌ

 

๐Ÿฏ ๋ชจ๋“  ์†Œ๋ฌธ์ž, ๋Œ€๋ฌธ์ž, ๋Œ€์†Œ๋ฌธ์ž, ์ˆซ์ž ๊ฐ€์ ธ์˜ค๊ธฐ

import string 

string.ascii_lowercase # ์†Œ๋ฌธ์ž abcdefghijklmnopqrstuvwxyz
string.ascii_uppercase # ๋Œ€๋ฌธ์ž ABCDEFGHIJKLMNOPQRSTUVWXYZ
string.ascii_letters #๋Œ€์†Œ๋ฌธ์ž ๋ชจ๋‘ abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
string.digits # ์ˆซ์ž 0123456789

 

๐Ÿฏ zip ํ•จ์ˆ˜ - ์—ฌ๋Ÿฌ๊ฐœ์˜ Iterable ๋™์‹œ์— ์ˆœํšŒ

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 )

 

๐Ÿฏ zip ํ•จ์ˆ˜ - ๋ฆฌ์ŠคํŠธ์—์„œ ๋”•์…”๋„ˆ๋ฆฌ ์ƒ์„ฑ

animals = ['cat', 'dog', 'lion']
sounds = ['meow', 'woof', 'roar']
answer = dict(zip(animals, sounds)) # {'cat': 'meow', 'dog': 'woof', 'lion': 'roar'}

 

๐Ÿฏ map - ๋ชจ๋“  ๋ฉค๋ฒ„์˜ type ๋ณ€ํ™˜ํ•˜๊ธฐ

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

 

๐Ÿฏ join - ๋ฉค๋ฒ„๋ฅผ ํ•˜๋‚˜๋กœ ์ด์–ด๋ถ™์ด๊ธฐ

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

 

๐Ÿฏ product - ๊ณฑ์ง‘ํ•ฉ ๊ตฌํ•˜๊ธฐ

from itertools import product

iterable1 = 'ABCD'
iterable2 = 'xy'
print(list(product(iterable1, iterable2)))
# [('A', 'x'), ('A', 'y'), ('B', 'x'), ('B', 'y'), ('C', 'x'), ('C', 'y'), ('D', 'x'), ('D', 'y')]

 

๐Ÿฏ permutations - ์ˆ˜์—ด ๋งŒ๋“ค๊ธฐ

from itertools import permutations

pool = ['A', 'B', 'C']
# 3๊ฐœ์˜ ์›์†Œ๋กœ ์ˆ˜์—ด ๋งŒ๋“ค๊ธฐ
print(list(map(''.join, permutations(pool)))) #['ABC', 'ACB', 'BAC', 'BCA', 'CAB', 'CBA']
# 2๊ฐœ์˜ ์›์†Œ๋กœ ์ˆ˜์—ด ๋งŒ๋“ค๊ธฐ
print(list(map(''.join, permutations(pool, 2)))) #['AB', 'AC', 'BA', 'BC', 'CA', 'CB']

 

๐Ÿฏ Counter - ์–ด๋–ค ์›์†Œ๊ฐ€ ๋ช‡๋ฒˆ ๋“ฑ์žฅํ•˜๋Š”์ง€

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) # Counter({1: 4, 2: 3, 3: 3, 7: 3, 4: 2, 5: 2, 6: 2, 8: 2, 9: 2, 0: 2})
print(answer[1]) # 4
print(answer[3])  # 3
print(answer[100]) # 0

 

๐Ÿฏ startswith, endswith - ์‹œ์ž‘ํ•˜๋Š” ๋ฌธ์ž, ๋๋‚˜๋Š” ๋ฌธ์ž ์—ฌ๋ถ€

s = '12345'

s.startswith('123')
# True
s.startswith('34')
#False
s.startswith('34', 2)
#True