0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

zip()関数は、2つ以上のイテラブルオブジェクト(リスト、タプル、文字列など)から要素を取り出し、対応する要素同士を組み合わせたイテレータを返します。

基本的な使い方

list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']

zipped = zip(list1, list2)
print(list(zipped))  # 出力: [(1, 'a'), (2, 'b'), (3, 'c')]

この例では、zip()関数に2つのリストを渡しています。返り値は、対応する要素同士をタプルにしたイテレータオブジェクトです。list()関数を使って、リストに変換しています。

複数のイテラブルを渡す

numbers = [1, 2, 3]
letters = ['a', 'b', 'c']
symbols = ['!', '@', '#']

zipped = zip(numbers, letters, symbols)
print(list(zipped))  # 出力: [(1, 'a', '!'), (2, 'b', '@'), (3, 'c', '#')]

3つ以上のイテラブルを渡すこともできます。返り値は、それぞれのイテラブルから取り出した要素をタプルにしたものになります。

並行してイテレートする

names = ['Alice', 'Bob', 'Charlie']
scores = [85, 92, 88]

for name, score in zip(names, scores):
    print(f'{name} scored {score} points.')

この例では、zip()関数を使って2つのリストを併せてイテレートしています。各繰り返しで、対応する名前とスコアが取り出されます。

イテラブルの長さが異なる場合

zip()関数は、最も短いイテラブルの長さまで要素を組み合わせます。

list1 = [1, 2, 3, 4, 5]
list2 = ['a', 'b', 'c']

zipped = zip(list1, list2)
print(list(zipped))  # 出力: [(1, 'a'), (2, 'b'), (3, 'c')]

この例では、list1の方が長いにもかかわらず、list2の長さ(3)に合わせて要素が組み合わされています。

zip()関数は、複数のイテラブルを扱う際に非常に便利です。辞書やリストの作成、並行したイテレーション処理など、さまざまな用途に使えます。イテラブルの長さが異なる場合の動作にも注意が必要です。

参考) 東京工業大学情報理工学院 Python早見表

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?