Python 리스트 기능

리스트 기능 정리

얕은 복사 vs 깊은 복사

a_list = [1, 2, 0, 4, 5] 
b_list = a_list     # 별칭 생성
c_list = a_list[:]  # 얕은 복사

a_list[2] = 3

print(b_list)       # [1, 2, 3, 4, 5]
print(c_list)       # [1, 2, 0, 4, 5]


import copy

a_list = [1, 2, [5, 10]]

b_list = a_list[:]  # 얕은 복사

b_list[0] = 0
b_list[1] = 0
b_list[2][0] = 0
b_list[2][1] = 0

print(a_list)       # [1, 2, [0, 0]]

c_list = copy.deepcopy(a_list)  # 깊은 복사

c_list[0] = 0
c_list[1] = 0
c_list[2][0] = 0
c_list[2][1] = 0

print(a_list)       # [1, 2, [5, 10]]

리스트 함수

len(리스트)
max(리스트)
min(리스트)
reversed(리스트)    # 역순으로 정렬된 이터레이터 반환
sorted(리스트)      # 정렬된 리스트 생성
sum(리스트)         # 모든 항목을 더한 값 반환, 숫자만 가능

리스트 메서드

리스트.append()
리스트.clear()          # 모든 항목 제거
리스트.extend(리스트)     # [1,2,3].extend([4,5]) => [1,2,3,4,5]
리스트.insert(인덱스, )
리스트.revome()       # 값의 첫 인스턴스 제거

리스트.count()        # 인스턴스 개수 반환
리스트.index()        # 값의 인덱스 반환
리스트.pop([인덱스])     # 인덱스의 값 반환 및 제거, default index = -1

리스트.sort([reverse=False])  # reverse=True 하면 정렬한 뒤에 뒤집음
리스트.reverse()        # 현재 순서를 뒤집음

후위표기법(RPN)

연산자를 피연산자 뒤에 위치시키는 언어

# 방법 1
the_stack = []

def push(v):
    the_stack.append(v)

def pop():
    return the_stack.pop()

def main():
    s = input('Enter RPN string: ')
    a_list = s.split()
    for item in a_list:
        if item in '+-*/':
            op2 = pop()
            op1 = pop()
            if item == '+':
                push(op1 + op2)
            elif item == '-':
                push(op1 - op2)
            elif item == '*':
                push(op1 * op2)
            else:
                push(op1 / op2)
        else:
            push(float(item))
    print(pop())


# 방법 2
the_stack = []

def main():
    s = input('Enter RPN string: ')
    a_list = s.split()
    for item in a_list:
        if item in '+-*/':
            op2 = the_stack.pop()
            op1 = the_stack.pop()
            if item == '+':
                the_stack.append(op1 + op2)
            elif item == '-':
                the_stack.append(op1 - op2)
            elif item == '*':
                the_stack.append(op1 * op2)
            else:
                the_stack.append(op1 / op2)
        else:
            the_stack.append(float(item))
    print(the_stack.pop())


# 방법 3
the_stack = []

def main():
    s = input('Enter RPN string: ')
    a_list = s.split()
    for item in a_list:
        if item in '+-*/':
            op2 = the_stack.pop()
            op1 = the_stack.pop()
            the_stack.append(eval(str(op1) + item + str(op2)))
        else:
            the_stack.append(float(item))
    print(the_stack.pop())

Lambda & reduce 함수

import functools

# functools.reduce(fuction, list)
# lambda arguments: return_value

t5 = functools.reduce(lambda x, y: x + y, [1,2,3,4,5])
print(t5)   # 15

List Comprehension

b_list = [i * i for i in a_list]

conditional_list = [i * i for i in a_list if i > 0]

mult_list = [i * j for i in range(3) for j in range(3)]

© 2023. All rights reserved.

Powered by Hydejack