1
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?

Pythonで効率的に複数リストを操作する方法: zip() の使い方

Posted at

ZIP()とは

複数のイテラブルを並行に反復処理し、各イテラブルの要素からなるタプルを生成します。この関数を使うことで、ループの中で複数のリストを簡潔に扱えるようになります。

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

(1, 'sugar')
(2, 'spice')
(3, 'everything nice')

zip() の基本的な使い方

zip() 関数は、複数のリストをタプルのペアとして結合し、イテラブル(繰り返し可能なオブジェクト)を返します。

names = ['Alice', 'Bob', 'Charlie']
scores = [85, 90, 95]

# zip()でリストを結合
for name, score in zip(names, scores):
    print(f"{name}: {score}")
# 出力:
# Alice: 85
# Bob: 90
# Charlie: 95
  • ポイント
    リストの長さが異なる場合、短い方の長さに合わせてトリムされます。

zip() の戻り値と展開

zip() が返すのはイテレータで、リストやタプルのようにそのまま使用できます。リスト形式に変換するには list() を使います。

  • zip() の結果をリスト化
names = ['Alice', 'Bob', 'Charlie']
scores = [85, 90, 95]

zipped = zip(names, scores)
zipped_list = list(zipped)

print(zipped_list)
# 出力: [('Alice', 85), ('Bob', 90), ('Charlie', 95)]
  • 複数リストを辞書に変換
keys = ['name', 'age', 'city']
values = ['Alice', 25, 'New York']

zipped = zip(keys, values)
result = dict(zipped)
print(result)
# 出力: {'name': 'Alice', 'age': 25, 'city': 'New York'}

例: リストの位置ごとに計算

list1 = [1, 2, 3]
list2 = [4, 5, 6]

# 対応する要素を足す
summed = [x + y for x, y in zip(list1, list2)]
print(summed)
# 出力: [5, 7, 9]

zip() の利点と注意点

  • 利点
    コードの簡潔化: 明示的なインデックス操作が不要。
    柔軟性: 様々なデータ構造の操作に対応。
  • 注意点
    リストの長さが異なると、トリムされる点に注意。
    zip() の戻り値はイテレータなので、再利用には再生成が必要。

1
0
1

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
1
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?