Programming 기초/Python

[python] 기억해 둘 파이썬 문법&개념

코딩상륙작전 2023. 8. 19. 23:17

* all, any

a=[False,True,True,False]
b=[False,False,False,False]
c=[True,True,True,True]
print(all(a))
print(all(b))
print(all(c))

print(any(a))
print(any(b))
print(any(c))
-------------------------
False
False
True
True
False
True

 

* isdigit, title

a="hello world do you know BTS?"
b='1234567'
print(a.isdigit())
print(a.title())    # 단어의 첫 문자만 upper. 나머진 lower
print(b.isdigit())  # 띄어쓰기가 들어가도 False
print(b.title())
---------------------
False
Hello World Do You Know Bts?
True
1234567

 

* raw-string : \를 쓰지 않고도 특수문자들을 그대로 출력할 수 있음.

print('it\'s me')
print(r"it's me")
-------------------
it's me
it's me

 

* call by object reference

파이썬은 객체의 주소가 함수로 전달되는 방식이 있음.

전달된 객체를 참조하여 변경 시 호출자에게 영향을 주나,

새로운 객체를 만들 경우 호출자에게 영향을 주지 않음.

def spam(eggs):
    eggs.append(1)  # 기존 객체의 주소값에 [1]추가
    eggs=[2,3]  # 새로운 객체 생성

ham=[0]
spam(ham)
print(ham)	# [0, 1]이 출력됨.

 

* tuple: 1개의 숫자를 튜플로 인식시키기 위해선 comma를 써줘야 함.

x=(1)
print(type(x))
y=(1,)
print(type(y))
-----------------
<class 'int'>
<class 'tuple'>

 

* deque.rotate() : 원소 위치를 하나씩 뒤로 옮긴다.

from collections import deque

x=[1,2,3,4,5]
deque_list = deque(x)
deque_list.append(6)
deque_list.append(7)
# deque_list.extend([6,7])과 같다.
print(deque_list)

deque_list.rotate(1)
print(deque_list)

deque_list.rotate(2)
print(deque_list)
----------------------
deque([1, 2, 3, 4, 5, 6, 7])
deque([7, 1, 2, 3, 4, 5, 6])
deque([5, 6, 7, 1, 2, 3, 4])

 

* defaultdict : key값을 생성할 때 따로 지정해주지 않으면 디폴트 값으로 key값을 만듦

from collections import defaultdict

d=defaultdict(lambda : 0)	# 함수를 받음.
print(d['a'])	# 0 출력
print(d['b'])	# 0 출력
# 위 defaultdict는 아래 dict()를 이용한 방식과 비슷하다.
dd=dict()
dd['a']=dd.get('a', 0)
dd['b']=dd.get('b', 0)
print(dd['a'])	# 0 출력
print(dd['b'])	# 0 출력

 

* magic method

https://corikachu.github.io/articles/python/python-magic-method

 

파이썬 더블 언더스코어: Magic Method | Corikachu

파이썬에서 __를 달고있는 메소드들에 대해서 살펴봅시다.

corikachu.github.io

 

* assert

bool값을 받아서 False면 Error발생.

assert True
print("Hello World")	# 출력됨.
assert False
print("Hello World")	# error 발생