Python实现按数字降序排序文本文件中的字符-数字条目
Hey there! Let's work through this together—since you're new to Python, I'll break it down into simple, actionable steps that build on the code you already have.
First, let's recap what you've got so far:
- A text file with entries like
asdf:15.3 eazzz:31.12 qw:1.65 - A function
get_num()that splits a string likeasdf:15.3and returns the numeric part as a float
Here's how to extend this to sort the entries by their numeric values in descending order, while keeping each label tied to its number:
Step 1: Read and Parse the File Content
First, we need to read the file, split it into individual entries, and pair each label with its number. Let's use your get_num() function here:
def get_num(str): items = str.split(':') return float(items[1]) # Read the file content (replace 'your_file.txt' with your actual file path) with open('your_file.txt', 'r') as file: content = file.read().strip() # Read all text and remove extra whitespace # Split content into individual entries (splits on any spaces) entries = content.split() # Create a list of tuples: (label, number) to keep each pair linked label_num_pairs = [] for entry in entries: label = entry.split(':')[0] number = get_num(entry) label_num_pairs.append( (label, number) )
If you want to make this a bit more concise (once you're comfortable with list comprehensions), you can shorten the pair creation step to:
label_num_pairs = [ (entry.split(':')[0], get_num(entry)) for entry in entries ]
Step 2: Sort the Pairs by Number (Descending)
Python's sorted() function is perfect for this. We'll use the key parameter to specify we want to sort by the numeric value of each pair, and reverse=True to get descending order:
# Sort the list by the second element of each tuple (the number), descending sorted_pairs = sorted(label_num_pairs, key=lambda x: x[1], reverse=True)
That lambda x: x[1] part is a tiny, one-time function that takes each tuple x (like ('eazzz', 31.12)) and returns the second element (the number) as the value to sort by.
Step 3: Use or Print the Sorted Results
Now you can loop through sorted_pairs to view the sorted entries, or format them however you need:
# Print each sorted entry in a readable format print("Sorted entries (descending by number):") for label, num in sorted_pairs: print(f"{label}:{num}") # Or if you want to convert them back to a single string like the original file: sorted_content = ' '.join([f"{label}:{num}" for label, num in sorted_pairs]) print("\nFormatted as a single string:") print(sorted_content)
Full Combined Script
Here's the complete script putting all steps together:
def get_num(str): items = str.split(':') return float(items[1]) # Read and process the file with open('your_file.txt', 'r') as file: content = file.read().strip() entries = content.split() label_num_pairs = [ (entry.split(':')[0], get_num(entry)) for entry in entries ] # Sort descending by numeric value sorted_pairs = sorted(label_num_pairs, key=lambda x: x[1], reverse=True) # Output the results print("Sorted entries (descending by number):") for label, num in sorted_pairs: print(f"{label}:{num}")
A quick note: If your file has extra spaces or empty lines, content.split() will automatically ignore them since it splits on any whitespace.
内容的提问来源于stack exchange,提问作者Daniel O A

