Pythonのzip()関数は、その中にデータを格納します。
この関数はイテレート可能な要素を入力として受け取り、出力としてイテレート可能なものを返します。
Python zip 関数に反復可能な要素が与えられない場合、空のイテレータを返します。
このように、反復可能な要素から要素を集約し、タプルの反復可能性を返します。
Python Zip() 関数のシンタックス:
zip(*iterators)
Python Zip() 関数 パラメータ:
コンテナ/反復子(リスト、文字列、その他)
zip() 関数によって返される値。
この関数は、対応するコンテナから値をマッピングした反復子オブジェクトを返します。
例 Pythonのzip()関数の基本的な理解
# initializing the input list city = [ "Pune", "Ajanta", "Aundh", "Kochi" ]
code = [ 124875, 74528, 452657, 142563 ]
# zip() to map values result = zip(city, code)
result = set(result)
print ("The zipped outcome is : ",end="")
print (result)
|
結果は以下の通りです。
The zipped outcome is : {('Ajanta', 74528), ('Kochi', 142563), ('Aundh', 452657), ('Pune', 124875)}
Python zip() 関数と複数のイテラブルの組み合わせ
Python zip() 関数に複数の反復子が渡された場合、関数はその反復子に対応する要素を含むタプルの反復子を返します。
例えば、以下の様になります。
numbers = [23,33,43]
input_list = ['five', 'six', 'seven']
# No iterables being passed to zip() functionoutcome = zip()
result = list(outcome)
print(result)
# Two iterables being passed to zip() functionoutcome1 = zip(numbers, input_list)
result1 = set(outcome1)
print(result1)
|
結果は以下の通りです。
[]
{(23, 'five'), (33, 'six'), (43, 'seven')}
Python の zip() 関数で反復可能な要素の長さが不等間隔の場合
numbers = [23, 33, 43]
input_list = ['one', 'two']
input_tuple = ('YES', 'NO', 'RIGHT', 'LEFT')
# the size of numbers and input_tuple is differentoutcome = zip(numbers, input_tuple)
result = set(outcome)
print(result)
result1 = zip(numbers, input_list, input_tuple)
outcome1 = set(result1)
print(outcome1)
|
結果を出力すると、以下の様になります。
{(33, 'NO'), (43, 'RIGHT'), (23, 'YES')}
{(23, 'one', 'YES'), (33, 'two', 'NO')}
zip()関数で値を解凍します。
演算子 `”*”‘ は、値を解凍するために使用されます。
alphabets = ['a', 'c', 'e']
number = [1, 7, 9]
result = zip(alphabets, number)
outcome = list(result)
print(outcome)
test, train = zip(*outcome)
print('test =', test)
print('train =', train)
|
結果は、以下の通りになります。
[('a', 1), ('c', 7), ('e', 9)]
test = ('a', 'c', 'e')
train = (1, 7, 9)
まとめ
今回は、Pythonのzip()関数の動作について理解しました。