DAILY JOURNAL

Python

117記事の記録。

2025年10月

  1. 【Python】rangeとenumerate

    rangeをfor文のイテラブルとして使用した時 enumerateをfor文のイテラブルとして使用した時 それぞれの違いについて見ていこう。 ソースコード range_enumerate · ki-hi-ro/python@8b3c8c0 for i in range(10): print(i) for index, value in enumerate(['a', 'b', 'c', 'd']): print(f"Index: {index}, Value: {value}") range(10)を使用した場合と、文字列のリストに対してenumerateを使用した場合のソースコード。 出力結果 0 1 2 3 4 5 6 7 8 9 Ind…

    【Python】mapはfor文で使用すると消費される

    リストの中身を一括で型変換できるmap。 そのmapオブジェクトをfor文のイテラブルとして使用すると消費されてしまう。 どういうことか?見ていこう。 ソースコード map.py · ki-hi-ro/python@92037c1 def print_ints(int_iterable): for x in int_iterable: print(x) print("消費された後のリスト:", list(int_iterable)) str_list = ['1', '2', '3', '4', '5'] int_map = map(int, str_list) print_ints(int_map) int_list = [int(x…

    【Python】pop

    リストの要素を削除することのできるpopメソッドについて見ていこう。 サンプルコード pop · ki-hi-ro/python@63f6f86 sample_list = [1, 2, 3, 4, 5] # 何も指定しない場合、最後の要素が削除される popped_element = sample_list.pop() print("Popped element:", popped_element) print("List after popping the last element:", sample_list) # インデックスを指定して要素を削除 popped_element_at_index = sample_list.pop(1)…

    【Python】リスト2つを比較して、もう一方のリストに存在しない要素のリストを作成する

    a_listとb_listがある。 a_listにあって、b_listにない要素のリストを作成する。 ソースコード not_in_others_list.py · ki-hi-ro/python@f07e63c a_list = ['apple', 'banana', 'cherry', 'date'] b_list = ['banana', 'date', 'fig', 'grape'] not_in_b_list = [item for item in a_list if item not in b_list] print("Items in a_list not in b_list:", not_in_b_list) no…

    【Python】indexメソッド

    indexメソッドは、リストやタプルの中で、指定した要素が最初に現れる位置(インデックス)を返すメソッド。 サンプルコード python/index.py at main · ki-hi-ro/python some_list = [1, 2, 3, 4, 5] index = some_list.index(3) print(f"The index of 3 in the list is: {index}") some_tuple = (10, 20, 30, 40, 50) index = some_tuple.index(40) print(f"The index of 40 in the tuple is: {index}") 以下のコ…