![]() |
|
[Tut] How to Sort a List of Tuples by Second Value - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] How to Sort a List of Tuples by Second Value (/thread-99234.html) |
[Tut] How to Sort a List of Tuples by Second Value - xSicKxBot - 04-18-2022 How to Sort a List of Tuples by Second Value In this article, you’ll learn how to sort a list of tuples by the second value in Python. To make it more fun, we have the following running scenario: BridgeTech is a bridge restoration company. They have asked you to sort and return the Top 10 elements from the Periodic Table based on the ‘Atomic Radius’ in descending order. Quote:The atomic radius of a chemical element is a measure of the size of its atom, usually the mean or typical distance from the center of the nucleus to the outermost isolated electron. Click here to download the Periodic Table. Save this file as Code: periodic_table.csv Question: How would you write the Python code to accomplish this task?We can accomplish this task by one of the following options:
Preparation Before any data manipulation can occur, one (1) new library will require installation.
To install this library, navigate to an IDE terminal. At the command prompt ( Code: $Code: $Code: $ pip install pandasHit the Code: <Enter>If the installation was successful, a message displays in the terminal indicating the same. Feel free to view the PyCharm installation guide for the required library. Add the following code to the top of each code snippet. This snippet will allow the code in this article to run error-free. Code: import numpy as np
from operator import itemgetter Note: The Code: operatorMethod 1: Use Sort and a Lambda To sort a list of tuples based on the second element, use Code: sort()Code: lambdaCode: tups.sort(key=lambda x: x[1], reverse=True)Here’s an example: Code: df = pd.read_csv('periodic_table.csv', usecols=['Name', 'AtomicRadius'])
tups = [tuple(x) for x in df.values.tolist()]
tups.sort(key=lambda x: x[1], reverse=True)
print(tups[0:10])The CSV file is read in preparation, and two (2) columns save to a DataFrame. The DataFrame then converts to a list of tuples ( Code: tupsWe are ready to sort! A https://blog.finxter.com/a-simple-introduction-of-the-lambda-function-in-python/ Code: lambdaCode: sort()Code: x[1]Code: reverse=TrueCode: tupsTo complete the process, slicing is performed, and the Top 10 elements are sent to the terminal. Output Code: [('Francium', 348.0), ('Cesium', 343.0), ('Rubidium', 303.0), ('Radium', 283.0), ('Potassium', 275.0), ('Barium', 268.0), ('Actinium', 260.0), ('Strontium', 249.0), ('Curium', 245.0), ('Californium', 245.0)]Method 2: Use Sort & Itemgetter To sort a list of tuples by the second element, use the Code: sort()Code: itemgetter()Code: tuples.sort(key=itemgetter(1), reverse=True)Here’s an example: Code: df = pd.read_csv('periodic_table.csv', usecols=['Name', 'AtomicRadius'])
tups = [tuple(x) for x in df.values.tolist()]
tups.sort(key=itemgetter(1), reverse=True)
print(tups[0:10])The CSV file is read in preparation, and two (2) columns save to a DataFrame. The DataFrame then converts to a List of Tuples ( Code: tupsWe are ready to sort! The Code: sort()Code: itemgetter(n)Code: nCode: (itemgetter(1)Code: reverse=TrueThe results save to Code: tupsTo complete the process, slicing is performed, and the Top 10 elements are sent to the terminal. Note: The Code: itemgetter()Code: lambdaCode: itemgetterMethod 3: Use Sorted & Lambda To sort a list of tuples by the second element, combine the functions Code: sorted()Code: lambdaCode: sorted(tups, key=lambda x:(x[1]), reverse=True)Code: tupsHere’s an example: Code: df = pd.read_csv('periodic_table.csv', usecols=['Name', 'AtomicRadius'])
tups = [tuple(x) for x in df.values.tolist()]
tups = sorted(tups, key=lambda x:(x[1]), reverse=True)
print(tups[0:10])The CSV file is read in preparation, and two (2) columns save to a DataFrame. The DataFrame then converts to a List of Tuples ( Code: tupsWe are ready to sort! A Code: lambdaCode: sorted()Code: x[1]Code: reverse=TrueCode: tupsTo complete the process, slicing is performed, and the Top 10 elements are sent to the terminal. Method 4: Use Bubble Sort To sort a List of Tuples by the second element, you can also modify a sorting algorithm from scratch such as Bubble Sort to access the second (or n-th) tuple value as a basis for sorting. Here’s an example: Code: df = pd.read_csv('periodic_table.csv', usecols=['Name', 'AtomicRadius'])
tups = [tuple(x) for x in df.values.tolist()] def sort_tuples_desc(tups, idx): length = len(tups) for i in range(0, length): for j in range(0, length-i-1): if (tups[j][idx] < tups[j + 1][idx]): tmp = tups[j] tups[j] = tups[j+1] tups[j+1] = tmp return tups
print(sort_tuples_desc(tups, 1)[0:10])The CSV file is read in preparation, and two (2) columns save to a DataFrame. The DataFrame then converts to a List of Tuples ( Code: tupsWe are ready to sort! A sort function Code: sort_tuples_descCode: tupsCode: idxThis function returns a List of Tuples sorted in descending order. To complete the process, slicing is performed, and the Top 10 elements are sent to the terminal. Summary These four (4) methods of sorting a List of Tuples based on the second element should give you enough information to select the best one for your coding requirements. Good Luck & Happy Coding! |