2.6 Tuple #Writing Idiomatic Python 3.1

oen·2022년 6월 16일
0

1. collections.namedtuple

namedtuples를 사용하면 index 대신 필드 이름으로 접근할 수 있다.

👎

# 'employees' 테이블
# 컬럼: name, manager, salary
def print_employee_info(db_connection):
    db_cursor = db_connection.cursor()
    results = db_cursor.excute('select * from eployees').fetchall()
    for row in results:
        print(row[0] + 's manager is ' + row[1])
 

index로 접근

👍

# 'employees' 테이블
# 컬럼: name, manager, salary

from collections import namedtuple

EmployeeRow = namedtuple('EmployeeRow', ['name', 'manater', 'salary'])
EMPLOYEE_INFO = '{name}"s manager is {manager}'


def print_employee_info(db_connection):
    db_cursor = db_connection.cursor()
    results = db_cursor.excute('select * from eployees').fetchall()
    for row in results:
        employee = EmployeeRow._make(row)
        print(EMPLOYEE_INFO.format(**employee._asdict))

2. 필요하지 않은 데이터는 _ 로 대체

👎

(age, temp) = get_user_info(user)
if age > 21:
    print('over 21')
    

👍

(age, _) = get_user_info(user)
if age > 21:
    print('over 21')
    

3. unpack

👎

l = ['dog', 'Fido']
animal = l[0]
print(animal)
dog

👍

l = ['dog', 'Fido']
(animal, name) = l
print(animal)
dog

4. 함수에서 여러 값을 리턴할 때 사용

👎

def calculate_min(value_list):
    return min(value_list)


def calculate_max(value_list):
    return max(value_list)


values = [10, 20]
min_value = calculate_min(values)
max_value = calculate_max(values)
print(min_value)
10

👍

def calculate(value_list):
    min_value = min(value_list)
    max_value = max(value_list)

    return min_value, max_value


values = [10, 20]
(min_value, max_value) = calculate(values)
print(min_value)
10
profile
🐾

0개의 댓글