DAILY JOURNAL

日々の記録

1,983記事の記録。

2025年10月

  1. 【Python】zipとアンパック

    数字と数字のローマ字のタプルのリストがある。 それをアンパックしたものをzipに渡したものをfor文のイテラブルとして使用する。 zipの処理が行われた要素を出力する。 ソースコード zip · ki-hi-ro/python@21d72c2 num_list = [(1, 'one'), (2, 'two'), (3, 'three')] for number in zip(*num_list): print(number) 出力結果 元のタプルの最初の要素のタプルと、元のタプルの二つ目の要素のタプルが生成された。 (1, 2, 3) ('one', 'two', 'three') アンパック *num_listは、[(1, 'one'),…

    【Python】all

    allで全てが条件に当てはまった時にTrueにすることができる。 ソースコード all · ki-hi-ro/python@2f22a34 for_all_list = [10, 20, 30, 40, 50] if all(x > 5 for x in for_all_list): print(f"全ての要素が5より大きいです: {for_all_list}") for_all_listは、数字のリスト。 allに、for_all_listの中身が5より大きいという条件を指定している。 出力結果 全ての要素が5より大きいので、以下のように出力される。 全ての要素が5より大きいです: [10, 20, 30, 40, 50]

    【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…