如何使用字符串作为自定义排序规则?适配比较函数的实现方法
Got it, let's work through this problem together. The core idea here is to turn that custom order string into a priority map—so we can easily look up which number is "higher" according to your rules. Here's how to do it step by step:
Step 1: Build a Priority Mapping Dictionary
First, we need to assign each digit a priority based on its position in the order string. Digits that appear earlier have higher priority (meaning they're "larger" in your rule). Also, if the same digit shows up multiple times in the string (like the two 9s in your example), we only keep its first occurrence position—since duplicates should have the same priority.
order = '8927391' # Create a map where each digit points to its first position in the order string priority_map = {} for position, digit in enumerate(order): if digit not in priority_map: priority_map[digit] = position
Step 2: Implement the Comparison Function
This function will take two numbers, convert them to strings (to match the keys in our priority map), then check their positions to see if the first number is "higher" than the second. We'll also add a quick check to make sure the input numbers are actually in your custom rule—this avoids unexpected errors.
def if_no_is_higher(no1, no2): # Convert numbers to strings to match our priority map keys str_no1 = str(no1) str_no2 = str(no2) # Optional: Validate inputs are in the custom order if str_no1 not in priority_map: raise ValueError(f"Number {no1} isn't in your custom sorting rule!") if str_no2 not in priority_map: raise ValueError(f"Number {no2} isn't in your custom sorting rule!") # Compare priorities: smaller position = higher priority (larger number) if priority_map[str_no1] < priority_map[str_no2]: return 'yes' else: return 'no'
Test It Out
Let's run through your example and a few more to make sure it works:
print(if_no_is_higher(8, 9)) # Outputs 'yes' — 8 is at position 0, 9 at 1, so 8 is higher print(if_no_is_higher(9, 2)) # Outputs 'yes' — 9 is at 1, 2 at 2 print(if_no_is_higher(1, 7)) # Outputs 'no' — 1 is at 6, 7 at 3 print(if_no_is_higher(9, 9)) # Outputs 'no' — Same position, so not higher
Bonus: Sort a List Using This Rule
If you ever need to sort an entire list of numbers with this custom order, you can use the priority map as the key for Python's built-in sorted() function:
numbers_to_sort = [1, 8, 3, 9, 7, 2] sorted_numbers = sorted(numbers_to_sort, key=lambda x: priority_map[str(x)]) print(sorted_numbers) # Outputs [8, 9, 2, 7, 3, 1] — matches your custom order perfectly
内容的提问来源于stack exchange,提问作者GuyOverThere

