Python3 エンジニア認定基礎試験 練習問題 Day26:組み込み関数(enumerate, zip)

【本日のミッション】

Day25では「組み込み関数(sorted の応用と key 引数)」を学びました。
今日は enumerate() と zip() を使って、ループ処理をさらに便利にする方法を学びましょう。


enumerate の基本

fruits = ["apple", "banana", "cherry"]

for i, fruit in enumerate(fruits):
    print(i, fruit)

出力結果

0 apple
1 banana
2 cherry

インデックス番号と要素を同時に取得できます。


zip の基本

names = ["Alice", "Bob", "Charlie"]
scores = [85, 90, 78]

for name, score in zip(names, scores):
    print(name, score)

出力結果

Alice 85
Bob 90
Charlie 95

複数のリストを同時に処理できます。


練習問題

次のコードを実行するとどうなるでしょうか?

names = ["Tom", "Jerry", "Spike"]
animals = ["cat", "mouse", "dog"]

for i, (name, animal) in enumerate(zip(names, animals)):
    print(i, name, animal)

選択肢

A)

0 Tom cat
1 Jerry mouse
2 Spike dog

B)

1 Tom cat
2 Jerry mouse
3 Spike dog

C)

0 ('Tom', 'Jerry', 'Spike') ('cat', 'mouse', 'dog')

D)

エラーになる

Python3 エンジニア認定基礎試験 練習問題 Day26:組み込み関数(enumerate, zip)

解答

A)
0 Tom cat
1 Jerry mouse
2 Spike dog

■■■スポンサーリンク■■■

解説

for i, (name, animal) in enumerate(zip(names, animals)):
    print(i, name, animal)
  • zip(names, animals) → [("Tom", "cat"), ("Jerry", "mouse"), ("Spike", "dog")]

  • enumerate でインデックスがつく →

    0 (“Tom”, “cat”)

    1 (“Jerry”, “mouse”)

    2 (“Spike”, “dog”)

👉 出力結果は

0 Tom cat
1 Jerry mouse
2 Spike dog

👉 正解は A)
0 Tom cat
1 Jerry mouse
2 Spike dog


✅ ポイント

  • enumerate() → インデックス番号付きでループできる

  • zip() → 複数リストを同時に処理できる

  • for i, (x, y) in enumerate(zip(…)) → インデックスとペアを一緒に扱える


次回予告

Day27では 組み込み関数(map, filter, reduce) を学びます。
データ処理が一気に効率的になりますよ!


参考

Python 3 エンジニア認定基礎試験 – Odyssey CBT
Python3 エンジニア認定基礎試験 出題範囲と学習プラン
Python3 エンジニア認定基礎試験 練習問題 Day1:変数の基本
Python3 エンジニア認定基礎試験 練習問題 Day2:変数の型(int型とstr型)
Python3 エンジニア認定基礎試験 練習問題 Day3:算術演算子と代入演算子
Python3 エンジニア認定基礎試験 練習問題 Day4:文字列の操作
Python3 エンジニア認定基礎試験 練習問題 Day5:比較演算子と論理演算子
Python3 エンジニア認定基礎試験 練習問題 Day6:if文(条件分岐)
Python3 エンジニア認定基礎試験 練習問題 Day7:ループ処理(for文・while文)
Python3 エンジニア認定基礎試験 練習問題 Day8:break文とcontinue文
Python3 エンジニア認定基礎試験 練習問題 Day9:リスト(list)の基本
Python3 エンジニア認定基礎試験 練習問題 Day10:リストの操作(append,remove,len など)
Python3 エンジニア認定基礎試験 練習問題 Day11:リストのスライス(部分取り出し)
Python3 エンジニア認定基礎試験 練習問題 Day12:タプル(tuple)の基本
Python3 エンジニア認定基礎試験 練習問題 Day13:辞書(dict)の基本
Python3 エンジニア認定基礎試験 練習問題 Day14:集合(set)の基本
Python3 エンジニア認定基礎試験 練習問題 Day15:関数の定義と呼び出し
Python3 エンジニア認定基礎試験 練習問題 Day16:関数のデフォルト引数とキーワード引数
Python3 エンジニア認定基礎試験 練習問題 Day17:可変長引数(*args, **kwargs)
Python3 エンジニア認定基礎試験 練習問題 Day18:関数のスコープ(ローカル変数とグローバル変数)
Python3 エンジニア認定基礎試験 練習問題 Day19:ネスト関数(関数の中の関数)
Python3 エンジニア認定基礎試験 練習問題 Day20:ラムダ式(無名関数)
Python3 エンジニア認定基礎試験 練習問題 Day21:組み込み関数(len, type, range など)
Python3 エンジニア認定基礎試験 練習問題 Day22:組み込み関数(sum,max,min,sorted)
Python3 エンジニア認定基礎試験 練習問題 Day23:文字列と組み込み関数(len,str,int,float)
Python3 エンジニア認定基礎試験 練習問題 Day24:組み込み関数(abs, round, pow)
Python3 エンジニア認定基礎試験 練習問題 Day25:組み込み関数(sorted の応用と key 引数)
Python3 エンジニア認定基礎試験 練習問題 Day26:組み込み関数(enumerate, zip)
Python3 エンジニア認定基礎試験 練習問題 Day27:組み込み関数(map, filter, reduce)
Python3 エンジニア認定基礎試験 練習問題 Day28:組み込み関数(any, all)

■■■スポンサーリンク■■■