Python에서 두 목록을 압축하는 방법


종종 Python에서 두 목록을 압축(또는 “병합”)하는 데 관심이 있을 수 있습니다. 다행히도 zip() 함수를 사용하면 이 작업을 쉽게 수행할 수 있습니다.

이 튜토리얼에서는 이 기능의 실제 사용에 대한 몇 가지 예를 보여줍니다.

예제 1: 동일한 길이의 두 목록을 단일 목록으로 압축

다음 구문은 길이가 같은 두 목록을 하나로 압축하는 방법을 보여줍니다.

 #define list a and list b
a = ['a', 'b', 'c']
b = [1, 2, 3]

#zip the two lists together into one list
list( zip (a,b))

[('a', 1), ('b', 2), ('c', 3)]

예 2: 동일한 길이의 두 목록을 사전으로 압축

다음 구문은 길이가 같은 두 목록을 사전으로 압축하는 방법을 보여줍니다.

 #define list of keys and list of values
keys = ['a', 'b', 'c']
values = [1, 2, 3]

#zip the two lists together into one dictionary
dict( zip (keys, values)) 

{'a': 1, 'b': 2, 'c': 3}

예제 3: 길이가 다른 두 목록 압축

두 목록의 길이가 다른 경우 zip()은 더 짧은 목록의 길이로 잘립니다.

 #define list a and list b
a = ['a', 'b', 'c', 'd']
b = [1, 2, 3]

#zip the two lists together into one list
list( zip (a,b))

[('a', 1), ('b', 2), ('c', 3)]

zip()이 가장 짧은 목록의 길이로 잘리는 것을 방지하려면 대신 itertools 라이브러리의 zip_longest() 함수를 사용할 수 있습니다.

기본적으로 이 함수는 누락된 값에 대해 “없음”을 채웁니다.

 from itertools import zip_longest

#define list a and list b
a = ['a', 'b', 'c', 'd']
b = [1, 2, 3]

#zip the two lists together without truncating to length of shortest list
list( zip_longest (a, b))

[('a', 1), ('b', 2), ('c', 3), ('d', None)]

그러나 fillvalue 인수를 사용하여 사용할 다른 채우기 값을 지정할 수 있습니다.

 #define list a and list b
a = ['a', 'b', 'c', 'd']
b = [1, 2, 3]

#zip the two lists together, using fill value of '0'
list( zip_longest (a, b, fillvalue= 0 ))

[('a', 1), ('b', 2), ('c', 3), ('d', 0)]

여기에서 zip_longest() 함수에 대한 전체 문서를 찾을 수 있습니다.

의견을 추가하다

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다