본문 바로가기
IT/Programming Language

[Python] 까먹을 만한 문법 정리

by FreeYourMind 2022. 3. 22.

** : 제곱

// : 나눈 값에서 정수만 추출

% : 나머지

 

word = 'Python'

word[-1]   # 마지막에서 첫번째 문자

word[2:5]  # 2번째부터 5번째 전까지의 문자열 : tho

word[-2:]  # 마지막에서 두번째부터 마지막까지 문자열 : on  

 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
 0   1   2   3   4   5   6
-6  -5  -4  -3  -2  -1

-> array도 비슷한 방식

 

if len(word) == 4:

 

for i in range(len(word)):

 

for ~ break ~ else : break가 걸리는 exception 경우가 나오지 않을 경우 else문 실행

 

match ~ case : switch문과 쓰이는 방식이 같음

a = {x for x in 'abracadabra' if x not in 'abc'} # set
tel = {'jack': 4098, 'sape': 4139}
tel['guido'] = 4127
del tel['sape']
tel['irv'] = 4127

list(tel)   # ['jack', 'guido', 'irv']
sorted(tel) # ['guido', 'irv', 'jack']
dict(sape=4139, guido=4127, jack=4098) # {'sape': 4139, 'guido': 4127, 'jack': 4098}
dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]) # {'sape': 4139, 'guido': 4127, 'jack': 4098}

{x: x**2 for x in (2, 4, 6)} # {2: 4, 4: 16, 6: 36}

 

count 

a = [1,2,3,1]
a.count(1) # 2

 

Counter

from collections import Counter

Counter('hello world') # Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})

Counter('hello world').most_common() # [('l', 3), ('o', 2), ('h', 1), ('e', 1), (' ', 1), ('w', 1), ('r', 1), ('d', 1)]

 

반복문 활용 기술

knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for k, v in knights.items(): # key, value 쌍 가져오기
	print(k, v)
    
for i, v in enumerate(['tic', 'tac', 'toe']):
	print(i, v)
    
questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers): # zip : 두 array의 data를 하나씩 뽑아냄
	print('What is your {0}?  It is {1}.'.format(q, a)) # What is your name?  It is lancelot. What is your quest?  It is the holy grail. What is your favorite color?  It is blue.
    
for i in reversed(range(1, 10, 2)):
	print(i) # 9 7 5 3 1

 

Class

class Dog:
    kind = 'canine'         # class variable shared by all instances
    def __init__(self, name):
        self.name = name    # instance variable unique to each instance

d = Dog('Fido')
e = Dog('Buddy')
d.kind                  # 'canine' shared by all dogs
e.kind                  # 'canine' shared by all dogs
d.name                  # 'Fido' unique to d
e.name                  # 'Buddy' unique to e

class Bag:
    def __init__(self):
        self.data = []

    def add(self, x):
        self.data.append(x)

    def addtwice(self, x):
        self.add(x)
        self.add(x)
class Mapping:
    def __init__(self, iterable):
        self.items_list = []
        self.__update(iterable)

    def update(self, iterable):
        for item in iterable:
            self.items_list.append(item)

    __update = update   # private copy of original update() method

class MappingSubclass(Mapping): # 상속

    def update(self, keys, values):
        # provides new signature for update()
        # but does not break __init__()
        for item in zip(keys, values):
            self.items_list.append(item)

 

 

 

 

출처

https://docs.python.org/3/tutorial/

https://wikidocs.net/2

https://www.daleseo.com/python-collections-counter/

 

 

 

 

'IT > Programming Language' 카테고리의 다른 글

[Python] Class  (0) 2022.04.15
[Python] 행렬 회전  (0) 2022.03.23
[Python] switch -> match  (0) 2022.03.22
Generic이란  (0) 2022.03.06
[Javascript] 비동기 처리 방식  (0) 2022.02.20

댓글