Advertisement
afrizalwahyuadi66

sort

May 15th, 2024
595
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.10 KB | None | 0 0
  1. # Read the file and store the data in a list of dictionaries
  2. def read_data(file_name):
  3.     with open(file_name, 'r') as f:
  4.         headers = f.readline().strip().split()
  5.         data = []
  6.         for line in f:
  7.             row = line.strip().split()
  8.             data.append({header: value for header, value in zip(headers, row)})
  9.     return data
  10.  
  11. # Define a function to sort the data
  12. def sort_data(data, column, order):
  13.     if order == 'asc':
  14.         return sorted(data, key=lambda x: x[column])
  15.     elif order == 'desc':
  16.         return sorted(data, key=lambda x: x[column], reverse=True)
  17.     else:
  18.         print("Invalid order. Please choose 'asc' or 'desc'.")
  19.  
  20. # Get user input for file name, column, and order
  21. file_name = input("Enter the file name (including .txt extension): ")
  22. column = input("Choose a column to sort (NIM, NAMA, NILAI): ")
  23. order = input("Choose an order (asc, desc): ")
  24.  
  25. # Read the data from the file
  26. data = read_data(file_name)
  27.  
  28. # Sort and print the data
  29. sorted_data = sort_data(data, column, order)
  30. for row in sorted_data:
  31.     print("{:<10} {:<15} {:<5}".format(row['NIM'], row['NAMA'], row['NILAI']))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement