본문 바로가기

Python

파이썬 Python 함수 정리 모음

📌 1. 객체 관련 함수

✅ id()

  • 객체의 고유 식별자(ID)를 반환합니다.

a = 10 print(id(a)) # 객체의 고유 ID 출력

✅ isinstance()

  • 객체가 특정 클래스나 데이터 타입의 인스턴스인지 확인합니다.

a = 10 print(isinstance(a, int)) # 출력: True

✅ type()

  • 객체의 타입을 반환합니다.

a = 10 print(type(a)) # 출력: <class 'int'>


📌 2. 반복문 관련 함수

✅ enumerate()

  • 리스트나 튜플 등을 반복하면서 각 요소의 인덱스와 값을 함께 반환합니다.

my_list = ['a', 'b', 'c'] for index, value in enumerate(my_list): print(index, value) # 출력: 0 a # 1 b # 2 c

✅ all()

  • 모든 요소가 True일 때 True를 반환합니다.

my_list = [True, True, True] print(all(my_list)) # 출력: True

✅ any()

  • 하나라도 True일 때 True를 반환합니다.

my_list = [False, True, False] print(any(my_list)) # 출력: True

✅ zip()

  • 여러 리스트를 병렬로 묶어서 튜플로 반환합니다.

a = [1, 2, 3] b = ['a', 'b', 'c'] for pair in zip(a, b): print(pair) # 출력: (1, 'a') # (2, 'b') # (3, 'c')


📌 3. 고급 데이터 구조 관련 함수

✅ sorted()

  • 리스트나 이터러블 객체를 정렬하여 새로운 리스트로 반환합니다. 원본 객체는 변경되지 않습니다.

my_list = [3, 1, 4, 1, 5] print(sorted(my_list)) # 출력: [1, 1, 3, 4, 5]

✅ reversed()

  • 순서를 반대로 뒤집은 이터러블 객체를 반환합니다.

my_list = [1, 2, 3] print(list(reversed(my_list))) # 출력: [3, 2, 1]

✅ all() / any()

  • all() : 모든 요소가 True이면 True를 반환.
  • any() : 하나라도 True이면 True를 반환.

print(all([True, True, False])) # 출력: False print(any([True, False, False])) # 출력: True

✅ sorted()

  • 데이터를 정렬하여 새로운 리스트를 반환합니다.

numbers = [5, 3, 8, 1] sorted_numbers = sorted(numbers) print(sorted_numbers) # 출력: [1, 3, 5, 8]


📌 4. 파일 및 디렉토리 관련 함수

✅ os.listdir()

  • 디렉토리 내의 파일 목록을 반환합니다.

import os print(os.listdir('.')) # 현재 디렉토리의 파일 목록 출력

✅ os.mkdir()

  • 새로운 디렉토리를 생성합니다.

import os os.mkdir("new_directory") # "new_directory"라는 디렉토리 생성

✅ os.remove()

  • 파일을 삭제합니다.

import os os.remove("file.txt") # "file.txt" 삭제

✅ os.path.exists()

  • 파일이나 디렉토리가 존재하는지 확인합니다.

import os print(os.path.exists("file.txt")) # 파일이 존재하면 True, 없으면 False


📌 5. 날짜 및 시간 관련 함수

✅ time()

  • 현재 시간을 초 단위로 반환합니다.

import time print(time.time()) # 출력: 현재 시간의 초 단위 타임스탬프

✅ sleep()

  • 지정한 시간 동안 프로그램을 일시 정지시킵니다.

import time time.sleep(2) # 2초 동안 정지

✅ datetime.now()

  • 현재 날짜와 시간을 반환합니다.

from datetime import datetime print(datetime.now()) # 출력: 현재 날짜와 시간

✅ strptime() / strftime()

  • 날짜 및 시간 문자열을 파싱하거나 형식을 지정하여 문자열로 변환합니다.

from datetime import datetime date_str = "2025-02-01" date_obj = datetime.strptime(date_str, "%Y-%m-%d") print(date_obj) # 출력: 2025-02-01 00:00:00 formatted_str = date_obj.strftime("%d-%m-%Y") print(formatted_str) # 출력: 01-02-2025


📌 6. 람다 함수

✅ lambda

  • 간단한 익명 함수를 생성합니다.

multiply = lambda x, y: x * y print(multiply(3, 4)) # 출력: 12

✅ filter()

  • 주어진 조건을 만족하는 요소만 필터링하여 반환합니다.

numbers = [1, 2, 3, 4, 5] even_numbers = filter(lambda x: x % 2 == 0, numbers)

print(list(even_numbers)) # 출력: [2, 4]

✅ map()

  • 주어진 함수로 모든 요소를 처리하여 새로운 리스트를 반환합니다.

numbers = [1, 2, 3, 4] squared = map(lambda x: x ** 2, numbers) print(list(squared)) # 출력: [1, 4, 9, 16]


📌 7. 예외 처리 관련 함수

✅ try/except

  • 예외 처리를 통해 오류를 처리합니다.

try: x = 1 / 0 except ZeroDivisionError as e: print("Error:", e) # 출력: Error: division by zero

✅ raise

  • 예외를 강제로 발생시킵니다.

raise ValueError("This is a custom error message.")


📌 8. 기타 유용한 함수

✅ all() / any()

  • all() : 모든 요소가 True일 때 True 반환.
  • any() : 하나라도 True일 때 True 반환.

print(all([True, True, False])) # 출력: False print(any([True, False, False])) # 출력: True

✅ getattr() / setattr()

  • 객체의 속성을 동적으로 조회하거나 설정합니다.

class Person: name = "Alice" person = Person() print(getattr(person, "name")) # 출력: Alice setattr(person, "name", "Bob") print(person.name) # 출력: Bob

✅ delattr()

  • 객체의 속성을 삭제합니다.

class Person: name = "Alice" person = Person() delattr(person, "name")


✅ collections 모듈의 유용한 함수들

  • Counter: 데이터의 등장 횟수를 세는 함수.

from collections import Counter data = ["apple", "banana", "apple"] counter = Counter(data) print(counter) # 출력: Counter({'apple': 2, 'banana': 1})

  • defaultdict: 기본 값을 제공하는 딕셔너리.

from collections import defaultdict d = defaultdict(int) d['key'] += 1 print(d) # 출력: defaultdict(<class 'int'>, {'key': 1})

'Python' 카테고리의 다른 글

파이썬 Python 함수 정리 모음  (0) 2025.02.01