all() と zip() を使ったチェック
このステップでは、ソート済みタプルと組み合わせて all()
と zip()
関数を使用し、より高度なチェックと比較を行う方法を学びます。
all()
関数は Python の組み込み関数で、イテラブル(iterable)のすべての要素が真である場合(またはイテラブルが空の場合)に True
を返します。この関数は、シーケンス内のすべての要素に対して条件が満たされているかどうかをチェックするためによく使用されます。
zip()
関数は別の Python の組み込み関数で、複数のイテラブルを引数として受け取り、タプルのイテレータを返します。各タプルには、入力されたイテラブルから対応する要素が含まれています。この関数は、異なるシーケンスの要素を比較やその他の操作のためにペアにするのに便利です。
これらの関数をソート済みタプルとともにどのように使用できるか見てみましょう。
- LabEx 環境の VS Code エディタを開きます。
~/project
ディレクトリにある既存の sort_tuple.py
ファイルを編集するか、存在しない場合は作成します。
- 次のコードを
sort_tuple.py
にコピーして貼り付けます。
## Checking if a tuple is sorted using all() and zip()
def is_sorted(data):
## zip(data, data[1:]) pairs consecutive elements
## all(x <= y for x, y in ...) checks if each pair is in ascending order
return all(x <= y for x, y in zip(data, data[1:]))
my_tuple1 = (1, 2, 3, 4, 5)
my_tuple2 = (5, 2, 8, 1, 9)
print("Tuple 1:", my_tuple1, "is sorted:", is_sorted(my_tuple1))
print("Tuple 2:", my_tuple2, "is sorted:", is_sorted(my_tuple2))
このコードでは、与えられたタプルが昇順にソートされているかどうかをチェックする is_sorted()
関数を定義しています。zip()
を使ってタプルの連続する要素をペアにし、all()
を使って各ペアが昇順になっているかどうかをチェックします。
スクリプトを実行するには、VS Code のターミナル(下部パネルにあります)を開き、次のコマンドを実行します。
python sort_tuple.py
次のような出力が表示されるはずです。
Tuple 1: (1, 2, 3, 4, 5) is sorted: True
Tuple 2: (5, 2, 8, 1, 9) is sorted: False
ご覧の通り、is_sorted()
関数はタプルがソートされているかどうかを正しく識別しています。
この例を拡張して、2 つのタプルをソートした後に同一であるかどうかをチェックしてみましょう。
## Checking if two tuples are identical after sorting
def are_identical_after_sorting(tuple1, tuple2):
return sorted(tuple1) == sorted(tuple2)
tuple_a = (3, 1, 4, 1, 5)
tuple_b = (1, 5, 1, 4, 3)
tuple_c = (1, 2, 3, 4, 5)
print("Tuple A:", tuple_a, "and Tuple B:", tuple_b, "are identical after sorting:", are_identical_after_sorting(tuple_a, tuple_b))
print("Tuple A:", tuple_a, "and Tuple C:", tuple_c, "are identical after sorting:", are_identical_after_sorting(tuple_a, tuple_c))
このコードを sort_tuple.py
ファイルに追加し、再度実行します。
python sort_tuple.py
出力には次の内容が含まれるはずです。
Tuple A: (3, 1, 4, 1, 5) and Tuple B: (1, 5, 1, 4, 3) are identical after sorting: True
Tuple A: (3, 1, 4, 1, 5) and Tuple C: (1, 2, 3, 4, 5) are identical after sorting: False
この例では、are_identical_after_sorting()
関数が 2 つのタプルが元の順序に関係なく同じ要素を含んでいるかどうかをチェックします。両方のタプルをソートし、ソートされたリストを比較します。