0
3

More than 1 year has passed since last update.

【Python】enumerateの使い方

Last updated at Posted at 2021-10-05

enumerateメソッドはlist, tuple, dictionaryに全部適用されます。

普通のfor文要素しか取り出せないが、
enumerateだと要素とindexの両方とも取り出せます。

1. List

db_names = ['MySQL', 'PostgreSQL', 'SQLite', 'MariaDB']

for index, db_name in enumerate(db_names):
    print(index, db_name)

"""
結果:
0 MySQL
1 PostgreSQL
2 SQLite
3 MariaDB
"""

2. Tuple

db_names_tp = ('MySQL', 'PostgreSQL', 'SQLite', 'MariaDB')

for index, db_name in enumerate(db_names_tp):
    print(index, db_name)

"""
結果:
0 MySQL
1 PostgreSQL
2 SQLite
3 MariaDB
"""

3. Dictionary

3.1 keyだけ取る

students = {"John": 'Computer Science', 
            "Clare": 'Biology', 
            "Adam": 'Chemistry'}

for index, name in enumerate(students):
    print(index, name)
"""
結果:
0 John
1 Clare
2 Adam
"""

3.2 keyもvalueも取る

for index, (name, major) in enumerate(students.items()):
    print(f'Student_id:{index}, {name}\'s major is {major}.')

"""
結果
Student_id:0, John's major is Computer Science.
Student_id:1, Clare's major is Biology.
Student_id:2, Adam's major is Chemistry.
"""

(name, major)の説明:
dictionary.itemsの戻り値は: listとして(key, value)のtupleが格納されます。

print(students.items())
dict_items([('John', 'Computer Science'), ('Clare', 'Biology'), ('Adam', 'Chemistry')])

以上です。

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