Python
 Computer >> コンピューター >  >> プログラミング >> Python

タプルをfloat要素でソートするPythonプログラム


この問題では、float要素を使用してタプル(float要素で構成される)をソートするタスクを実行します。ここでは、組み込みの並べ替え方法()を使用し、その場で並べ替える方法を使用してこれを行う方法を説明します。

Input:
tuple = [('AAA', '10.265'), ('BBB', '24.107'), ('CCC', '26.541'), ('DDD', '14.256'), ('EEE', '11.365')]
Output:
[('CCC', '26.541'), ('BBB', '24.107'), ('DDD', '14.256'), ('EEE', '11.365'), ('AAA', '10.265')]

アルゴリズム

Step 1: Given a list.
Step 2: To sort using sorted ().
Step 3: Sequence (list, tuple, string) or collection (dictionary, set, frozenset) or any other iterator that needs to be sorted.
Step 4: Key(optional) is a function that would serve as a key or a basis of sort comparison.
Step 5: If Reverse (optional) is true, then the iterable would be sorted in reverse (descending) order, by default it is set as false.

サンプルコード

# Python code to sort a tuples by its float element
def tuplesort(A):
   return(sorted(A, key = lambda x: float(x[1]), reverse = True))
   # Driver Code
   A = [('Adwaita', '19.215'), ('Aadrika', '10.117'), ('Babai', '14.589'), ('Mona', '14.216'), ('Sanj', '8.365')]
print("Sort of Tuples By Its Float Number ::",tuplesort(A))

出力

Sort of Tuples By Its Float Number :: [('Adwaita', '19.215'), ('Babai', '14.589'), ('Mona', '14.216'), ('Aadrika', '10.117'), ('Sanj', '8.365')]

  1. バブルソート用のPythonプログラム

    この記事では、バブルソートの並べ替え手法の実装について学習します。 次の図は、このアルゴリズムの動作を示しています- アプローチ 最初の要素(インデックス=0)から始めて、現在の要素を配列の次の要素と比較します。 現在の要素が配列の次の要素よりも大きい場合は、それらを交換します。 現在の要素が次の要素よりも小さい場合は、次の要素に移動します。 手順1を繰り返します。 次に、以下の実装を見てみましょう- 例 def bubbleSort(ar):    n = len(arr)    # Traverse through

  2. 選択ソート用のPythonプログラム

    この記事では、Python3.xでの選択ソートとその実装について学習します。またはそれ以前。 選択ソート アルゴリズムでは、配列は、ソートされていない部分から最小要素を再帰的に見つけて、それを先頭に挿入することによってソートされます。特定の配列での選択ソートの実行中に、2つのサブ配列が形成されます。 すでにソートされているサブアレイ ソートされていないサブアレイ。 選択ソートを繰り返すたびに、ソートされていないサブアレイの最小要素がポップされ、ソートされたサブアレイに挿入されます。 アルゴリズムの視覚的表現を見てみましょう- それでは、アルゴリズムの実装を見てみましょう- 例