중첩 리스트 컴프리헨션 & zip()

Kaydenna92·2023년 4월 17일
0

Python

목록 보기
6/10

중첩된 리스트 컴프리헨션

  • 위의 코드는 다시 아래의 코드와 같다.
transposed = []

for i in range(4):
	transposed_row = []
    for row in matrix:
    	transposed_Row.append(row[i])
    transposed.append(transposed_row)
    
    
# 혹은
transposed = []
for i in range(4):
	transposed.append([row[i] for row in matrix])

# 더 간단하게 -> zip() 함수를 사용한다
list(zip(*matrix))

zip()

Iterate over several iterables in parallel, producing tuples with an item from each one.

for item in zip([1, 2, 3], ['sugar', 'spice', 'everything nice']):
	print(item)
# (1, 'sugar')
# (2, 'spice')
# (3, 'everything nice')

By default, zip() stops when the shortest iterable is exhausted. It will ignore the remaining items in the longer iterables, cutting off the result to the length of the shortest iterable:

list(zip(range(3), ['fee', 'fi', 'fo', 'fum']))
# [(0, 'fee'), (1, 'fi'), (2, 'fo')]

zip() is often used in cases where the iterables are assumed to be of equal length. In such cases, it’s recommended to use the strict=True option. Its output is the same as regular zip():

list(zip(('a', 'b', 'c'), (1, 2, 3), strict = True))
# [('a', 1), ('b', 2), ('c', 3)]

Unlike the default behavior, it raises a ValueError if one iterable is exhausted before the others:

for item in zip(range(3), ['fee', 'fi', 'fo', 'fum'], strict = True):
	print(item)
# (0, 'fee')
# (1, 'fi')
# (2, 'fo')
# error !
Traceback (most recent call last):
...
valueError : zip() argument 2 is longer than argument 1

Without the strict=True argument any bug that results in iterables of different lengths will be silenced, possibly manifesting as a hard-to-find bug in another part of the program.

zip()을 * 연산자와 함께 쓰면 리스트를 unzip 할 수 있다.

x = [1, 2, 3]
y = [4, 5, 6]
list(zip(x, y)) # [(1, 4), (2, 5), (3, 6)]
x2, y2 = zip(*zip(x, y))
x == list(x2) and y == list(y2) # True
profile
persistently

0개의 댓글