PS/PL 활용

Python 리스트 언패킹

kimyoungrok 2024. 6. 19. 00:36
728x90

Unpacking

Python에서 리스트의 요소를 언패킹하여 별도의 변수로 담아주는 여러 방법에 대해 알아보자.

 

리스트 ➡️ 변수

리스트의 요소를 각 변수에 할당하는 방법이다. 리스트의 요소 갯수만큼 변수가 필요하다.

numbers = [1, 2, 3]
a, b, c = numbers
print(a, b, c)  # 출력: 1 2 3

 

 

튜플 ➡️ 변수

리스트와 동일하다. 

numbers = (1, 2, 3)
a, b, c = numbers
print(a, b, c)  # 출력: 1 2 3

 

튜플에서 변수로 언패킹 하는 방법은 아래와 같이 응용할 수 있다.

 

문자열 포멧 출력문의 경우 인자로 tuple을 받는다.

따라서 입력으로 받은 words 리스트를 튜플로 변환하여 출력문의 각 인자로 쉽게 전달할 수 있다.

words = [...]
print("Latitude %d:%d:%d\nLongitude %d:%d:%d" % tuple(words))

 

 

[백준 05340] Secret Location [Python]

문제Someone is waiting at a secret location and has sent a text message with the coordinates of their location. The message contains the latitude and longitude coordinates in degrees, minutes, and seconds. Of course, the message is encoded so you must wr

kyr-db.tistory.com

 


Extended Iterable Unpacking (Python 3.0)

일반적으로 extended unpacking이라고 불린다.

리스트나 튜플 등 시퀀스 타입의 자료구조를 언패킹할 때, 특정 위치의 요소들을 개별 변수로 분리하고 나머지 요소들을 리스트로 받을 수 있도록 하는 기능이다.

 

PEP 3132 – Extended Iterable Unpacking | peps.python.org

This PEP proposes a change to iterable unpacking syntax, allowing to specify a “catch-all” name which will be assigned a list of all items not assigned to a “regular” name.

peps.python.org

 

아래와 같이 리스트의 numbers의 1, 2번 요소를 a, b에 담고 남은 요소를 rest에 리스트로 할당해준다.

numbers = [1, 2, 3, 4, 5]
a, b, *rest = numbers
print(a)      # 출력: 1
print(b)      # 출력: 2
print(rest)   # 출력: [3, 4, 5]

 

아래는 다차원 리스트의 요소 추출의 예시다.

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

first, *middle, last = matrix
print(first)   # 출력: [1, 2, 3]
print(middle)  # 출력: [[4, 5, 6]]
print(last)    # 출력: [7, 8, 9]

 

 

다음과 같이 활용할 수 있다.

numbers = [1, 2, 3]
print(numbers) # 출력: [1, 2, 3]

print(*numbers) # 출력: 1, 2, 3

numbers = list(map(int, input().split())
numbers = [*map(int, input().split()]

no, *content = [*input().split()] # 입력: ["P01", "content01", "content02"]
# no = "P01"
# content = ["content01", "content02"]

def sum(a, b):
    return a + b
    
numbers = [1, 2]
print(sum(*numbers)) # 출력: 3

 

 


 

728x90