0
0

More than 1 year has passed since last update.

python の zip 関数の動き

Posted at

zipが何をしているか?

zipがどのように動くか気になったのでpythonチュートリアルで調べた。

pythonチュートリアル 5. データ構造より抜粋

matrix = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
]
print(list(zip(*matrix)))

[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]

ネストしたfor

vec = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
list = [num for elem in vec for num in elem]
list = []
for elem in vec:
     print(elem)
     for num in elem:
         print(num)
         list.append(num)
print(list)

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

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

list_first = [[row[i] for row in matrix] for i in range(4)]
list_first = []
for i in range(4):
     print(f'first:{list_first}')
     list_second = []
     for row in matrix:
         list_second.append(row[i])
         print(f'matrix → second:{list_second}')
     list_first.append(list_second)
     print(f'first → second:{list_first}')
print(list_first)

first:[]
matrix → second:[1]
matrix → second:[1, 5]
matrix → second:[1, 5, 9]
first → second:[[1, 5, 9]]
first:[[1, 5, 9]]
matrix → second:[2]
matrix → second:[2, 6]
matrix → second:[2, 6, 10]
first → second:[[1, 5, 9], [2, 6, 10]]
first:[[1, 5, 9], [2, 6, 10]]
matrix → second:[3]
matrix → second:[3, 7]
matrix → second:[3, 7, 11]
first → second:[[1, 5, 9], [2, 6, 10], [3, 7, 11]]
first:[[1, 5, 9], [2, 6, 10], [3, 7, 11]]
matrix → second:[4]
matrix → second:[4, 8]
matrix → second:[4, 8, 12]
first → second:[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

組み込み関数のzipと同じ動きをする

matrix = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
]
print(list(zip(*matrix)))

[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]

unpackについて

アンパックも曖昧だったので記載した。

a = list(range(3, 6))
print(a)

[3, 4, 5]

args = [3, 6]
b = list(range(*args))
print(b)

[3, 4, 5]

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0