옆히

Python 기록용 본문

카테고리 없음

Python 기록용

옆집히드라 2024. 9. 6. 02:00

#데이터 타입

del ,append, extend

0.숫자형, 문자형

 

1.리스트 [1, 2, 3]

 

2.튜플->리스트와 달리 변경 불가 대입시 괄호 생략 가능 (1, 2, 3)

 

3.딕셔너리 {key1:value1, key2:value2, key3:value3}
중복되는 키는 무시함

키에 리스트는 사용불가함(immutable한 객체만 사용 가능함)
list(a.keys()) //키리스트 만들기

a.values() //밸류리스트 만들기

a.items() //키 아이템 쌍 얻기

.clear(), .get('key', 'default value)

'name' in a //키가 딕셔너리 안에 있는지 조사

 

4.집합

>>> s1 = set([1, 2, 3]) 셋키워드로 생성

>>> { 1, 2, 3 }

집합은 중복을 허용하지 않고, 순서가 없음

교집합  a ^& b, a.intersection(b)

합집합 a | b, a.union(b)

차집합 a - b, a.difference(b)

.add(1), .update([1, 2, 3 ]), .remove(1) 특정값 제거

 

5.불 -> 빈 객체면false

#deep copy
1.use [:]
2.use copy module

#조건부 평가식
b = a if a > 5 else 0

#lambda expression
add = lambda x, y: x + y

#list comprehension
a = [1, 2, 3, 4]
b = [k * 3 for k in a if num % 2 == 0)

#[expression for item in iterableObj if statement]

def match_complex(x):
    match x:
        case (0, y):
            return f"First value is zero, second value is {y}"
        case (1, _):
            return "First value is one"
        case _:
            return "No match"

result = match_complex((0, 42))
print(result)  # 출력: First value is zero, second value is 42

#입력 매개변수 여러개
def add(*args):
    result = 0
    for i in args:
        result += i
    return result

#키워드 매개변수
def print_kwargs(**kwargs):
    print(kwargs)
    
#출력   
#>>> print_kwargs(a=1)
#{'a': 1}
#>>> print_kwargs(name='foo', age=3)
#{'age': 3, 'name': 'foo'}

 

초기화하고 싶은 매개변수는 뒤에 작성

global 명령어를 사용하면 함수 밖의 변수에 접근이 가능

 

# 리스트의 각 요소에 2를 곱하는 예제
numbers = [1, 2, 3, 4]
doubled = map(lambda x: x * 2, numbers)
print(list(doubled))  # 출력: [2, 4, 6, 8]

# 리스트에서 짝수만 필터링하는 예제
numbers = [1, 2, 3, 4, 5, 6]
evens = filter(lambda x: x % 2 == 0, numbers)
print(list(evens))  # 출력: [2, 4, 6]

from functools import reduce

# 리스트의 모든 요소를 더하는 예제
numbers = [1, 2, 3, 4]
total = reduce(lambda x, y: x + y, numbers)
print(total)  # 출력: 10

# 리스트에서 특정 값의 개수를 세는 예제
numbers = [1, 2, 3, 1, 1, 4]
count_ones = numbers.count(1)
print(count_ones)  # 출력: 3

# 리스트의 합을 구하는 예제
numbers = [1, 2, 3, 4]
total = sum(numbers)
print(total)  # 출력: 10

# 리스트의 최댓값을 구하는 예제
numbers = [1, 2, 3, 4]
maximum = max(numbers)
print(maximum)  # 출력: 4

#메서드 체이닝을 사용하는 사용자 정의 클래스
class MyList:
    def __init__(self, lst):
        self.lst = lst

    def map(self, func):
        self.lst = list(map(func, self.lst))
        return self  # 메서드 체이닝을 위해 self 반환

    def filter(self, func):
        self.lst = list(filter(func, self.lst))
        return self

    def reduce(self, func, initializer=None):
        from functools import reduce
        self.lst = [reduce(func, self.lst, initializer)] if initializer else [reduce(func, self.lst)]
        return self

    def result(self):
        return self.lst

# 메서드 체이닝 사용 예
numbers = MyList([1, 2, 3, 4, 5, 6])

result = numbers.map(lambda x: x * 2).filter(lambda x: x % 4 == 0).reduce(lambda x, y: x + y).result()
print(result)  # 출력: [20]

 

파이썬의 메서드 체이닝(python metho.. : 네이버블로그 (naver.com)