0
2

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 enumerate()関数で for ループが変わる:インデックスと要素を同時に扱うコツ

Posted at

はじめに

Pythonのfor文は非常に便利ですが、時にはリストの要素と同時にそのインデックスも必要になることがあります。そんな時に活躍するのがenumerate()関数です。この記事では、enumerate()関数の使い方とそのメリットについて解説します。

image.png

enumerate()関数とは?

enumerate()は、イテラブル(リストやタプルなど)を受け取り、各要素のインデックスと値のペアを返すイテレータを生成する関数です。

基本的な使い方

fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
    print(f"Index {index}: {fruit}")

出力:

Index 0: apple
Index 1: banana
Index 2: cherry

enumerate()のメリット

  1. コードの可読性向上
  2. インデックスの手動管理が不要
  3. エラーの可能性を減らす

応用例

1. 開始インデックスの指定

fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits, start=1):
    print(f"{index}番目の果物: {fruit}")

出力:

1番目の果物: apple
2番目の果物: banana
3番目の果物: cherry

2. 辞書の作成

fruits = ['apple', 'banana', 'cherry']
fruit_dict = dict(enumerate(fruits))
print(fruit_dict)

出力:

{0: 'apple', 1: 'banana', 2: 'cherry'}

3. リスト内包表記との組み合わせ

fruits = ['apple', 'banana', 'cherry']
squared_indices = [i**2 for i, _ in enumerate(fruits)]
print(squared_indices)

出力:

[0, 1, 4]

より魅力的な使用例

4. CSVファイルの行番号付き読み込み

import csv

# サンプルCSVファイルの内容
# Name,Age,City
# Alice,25,New York
# Bob,30,London
# Charlie,35,Tokyo

with open('data.csv', 'r') as file:
    for line_num, row in enumerate(csv.reader(file), start=1):
        print(f"Line {line_num}: {row}")

出力:

Line 1: ['Name', 'Age', 'City']
Line 2: ['Alice', '25', 'New York']
Line 3: ['Bob', '30', 'London']
Line 4: ['Charlie', '35', 'Tokyo']

5. 重複要素の検出

def find_duplicates(items):
    seen = set()
    duplicates = []
    for index, item in enumerate(items):
        if item in seen:
            duplicates.append((index, item))
        else:
            seen.add(item)
    return duplicates

numbers = [1, 2, 3, 2, 4, 1, 5, 6, 3]
result = find_duplicates(numbers)
for index, value in result:
    print(f"重複: インデックス {index} の値 {value}")

出力:

重複: インデックス 3 の値 2
重複: インデックス 5 の値 1
重複: インデックス 8 の値 3

6. 複数のリストの同時処理

names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
cities = ['New York', 'London', 'Tokyo']

for i, (name, age, city) in enumerate(zip(names, ages, cities), start=1):
    print(f"Person {i}: {name} is {age} years old and lives in {city}")

出力:

Person 1: Alice is 25 years old and lives in New York
Person 2: Bob is 30 years old and lives in London
Person 3: Charlie is 35 years old and lives in Tokyo

7. テキスト処理:行番号付きの単語カウント

text = """
Python is amazing
It makes coding fun
Enumerate is useful
"""

word_counts = {}
for line_num, line in enumerate(text.split('\n'), start=1):
    words = line.split()
    for word in words:
        if word not in word_counts:
            word_counts[word] = []
        word_counts[word].append(line_num)

for word, lines in word_counts.items():
    print(f"'{word}' appears in lines: {lines}")

出力:

'Python' appears in lines: [2]
'is' appears in lines: [2, 4]
'amazing' appears in lines: [2]
'It' appears in lines: [3]
'makes' appears in lines: [3]
'coding' appears in lines: [3]
'fun' appears in lines: [3]
'Enumerate' appears in lines: [4]
'useful' appears in lines: [4]

まとめ

image.png

enumerate()関数は、単純なインデックス付けから複雑なデータ処理まで、幅広い用途に活用できる強力なツールです。これらの例を参考に、自分のコードでもenumerate()を積極的に活用してみてください。コードの可読性と効率性が大幅に向上するはずです。

参考資料

0
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?