Programming/python

2023년 3월 파이썬 문법 - 공부 기록

방황하는 데이터불도저 2023. 3. 6. 00:39

* 리스트 속의 리스트에서의 min, max 활용법

dots = [[1, 4], [9, 2], [3, 8], [11, 6]]

min(dots)   # [1, 4]
max(dots)   # [11, 6]

* 문자열 속의 패턴 찾기

import re

s = "apple, banana"

re.findall("a", s)
# Output : ["a", "a", "a", "a"]
# s 안의 모든 a를 찾아서 리스트로 반환함

* 두 값의 최대공약수를 구하는 법 (Greatest Common Divisor)

from math import gcd

a = 10
b = 15

gcd(a,b)    # 5

* 두 값의 최소공배수를 구하는 법 (Least/Lowest Common Multiple)

from math import lcm

a = 10
b = 15

lcm(a,b)    # 30

* 파이썬 문법 := (바다코끼리 연산자; the walrus operator)

   - 더 큰 표현식의 일부로 변수에 값을 대입 문법   https://docs.python.org/ko/3/whatsnew/3.8.html  

if (a := 10) < 20:
	print(f"{a} is less than 20.")
# Output : 10 is less than 20.

if (a := 10) < (b := 20):
	print(f"{a} is less than {b}.")
# Output : 10 is less than 20.

* 변수의 type 일치관계 확인하는 방법

x1 = 1.234
isinstance(x1, float)  # True

x2 = 1234
isinstance(x2, int)    # True