数字と数字のローマ字のタプルのリストがある。 それをアンパックしたものを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'),…
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]
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…
リストの中身を一括で型変換できる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…
リストの要素を削除することのできる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)…
git pushをしたら、以下のエラーが発生した。 hiroki@shibatahiroshitakanoMacBook-Air ki-hi-ro.com % git push fatal: The current branch main has no upstream branch. To push the current branch and set the remote as upstream, use git push --set-upstream origin main To have this happen automatically for branches without a tracking upstream, see 'push.a…
集合A ^ 集合Bで、集合Aと集合Bの差の集合ができる。 ソースコード symmetric_difference.py · ki-hi-ro/python@2f5ca39 set_a = {1, 2, 3, 4, 5} set_b = {2, 3} symmetric_diff = set_a ^ set_b print("Symmetric difference between set_a and set_b:", symmetric_diff) symmetric_diffに集合の対称差が入る。 実行結果 Symmetric difference between set_a and set_b: {1, 4, 5} set_aとset_bの対称差は…
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…