杰瑞科技汇

Python字符串如何排序?

Of course! Sorting strings in Python is a common task, and Python provides powerful and flexible ways to do it. The main tool you'll use is the built-in sorted() function, and the .sort() method for lists.

Python字符串如何排序?-图1
(图片来源网络,侵删)

Here’s a complete guide, from the basics to more advanced sorting techniques.

The Basics: Using sorted() and .sort()

There are two primary ways to sort strings:

  • sorted(my_string): Returns a new sorted list of the characters in the string. The original string is unchanged.
  • my_list_of_strings.sort(): Sorts a list of strings in-place, modifying the original list. This method does not return anything.

Example 1: Sorting the characters within a single string

my_string = "python"
# sorted() returns a new list of sorted characters
sorted_chars = sorted(my_string)
print(f"Original string: {my_string}")
print(f"Sorted list of characters: {sorted_chars}")
# Output: Sorted list of characters: ['h', 'n', 'o', 'p', 't', 'y']
# To get back a sorted string, you must join the list
sorted_string = "".join(sorted_chars)
print(f"Sorted string: {sorted_string}")
# Output: Sorted string: hnopty

Example 2: Sorting a list of strings

languages = ["Python", "Java", "C++", "Ruby", "Go"]
# sorted() returns a new sorted list
sorted_languages = sorted(languages)
print(f"Original list: {languages}")
print(f"New sorted list: {sorted_languages}")
# Output: New sorted list: ['C++', 'Go', 'Java', 'Python', 'Ruby']
# The .sort() method sorts the list in-place
languages.sort()
print(f"List after .sort(): {languages}")
# Output: List after .sort(): ['C++', 'Go', 'Java', 'Python', 'Ruby']

Advanced Sorting with the key Argument

This is where Python's sorting power really shines. The key argument allows you to specify a function to be called on each element prior to making comparisons. This means you can sort by custom criteria.

Key Functions for Common String Sorting Tasks

Task Key Function Example key= Value
Case-Insensitive Sort str.lower or str.upper key=str.lower
Sort by Length len key=len
Sort by Reverse Length len (with reverse=True) key=len, reverse=True
Sort by Last Character lambda s: s[-1] key=lambda s: s[-1]
Sort by Number Suffix (e.g., "file2") lambda s: int(s.split('e')[-1]) key=lambda s: int(s[-1])

A) Case-Insensitive Sorting

By default, Python sorts uppercase letters before lowercase letters ('A' < 'a').

Python字符串如何排序?-图2
(图片来源网络,侵删)
words = ["apple", "Banana", "cherry", "Date"]
# Default sort (A-Z, then a-z)
default_sort = sorted(words)
print(f"Default sort: {default_sort}")
# Output: Default sort: ['Banana', 'Date', 'apple', 'cherry']
# Case-insensitive sort
case_insensitive_sort = sorted(words, key=str.lower)
print(f"Case-insensitive sort: {case_insensitive_sort}")
# Output: Case-insensitive sort: ['apple', 'Banana', 'cherry', 'Date']

B) Sorting by Length

You can sort strings based on how many characters they have.

words = ["cat", "elephant", "dog", "mouse"]
# Sort by length (shortest to longest)
by_length = sorted(words, key=len)
print(f"Sorted by length: {by_length}")
# Output: Sorted by length: ['cat', 'dog', 'mouse', 'elephant']
# Sort by length (longest to shortest)
by_length_desc = sorted(words, key=len, reverse=True)
print(f"Sorted by length (descending): {by_length_desc}")
# Output: Sorted by length (descending): ['elephant', 'mouse', 'cat', 'dog']

C) Sorting by a Custom Logic (Lambda Function)

Imagine you have filenames and want to sort them by their number.

files = ["file10.txt", "file2.txt", "file1.txt"]
# Default sort will be lexicographical, not numerical
default_sort = sorted(files)
print(f"Default sort: {default_sort}")
# Output: Default sort: ['file1.txt', 'file10.txt', 'file2.txt'] (Wrong!)
# Correct sort: extract the number and sort by it
# We use a lambda function to get the number part and convert it to an int
numerical_sort = sorted(files, key=lambda s: int(s.split('e')[-1].split('.')[0]))
print(f"Numerical sort: {numerical_sort}")
# Output: Numerical sort: ['file1.txt', 'file2.txt', 'file10.txt']

In-Place vs. New List: A Quick Summary

Method What it Does Returns Modifies Original?
sorted(my_list) Returns a new list containing all items from the iterable in sorted order. The new sorted list No
my_list.sort() Sorts the list in-place, changing the order of its elements. None Yes

Rule of Thumb:

  • Use sorted() when you need a new sorted list and want to keep the original intact.
  • Use .sort() when you are sure you don't need the original order anymore and want to save memory (since it doesn't create a new list).

Complete Example: Sorting a Complex List of Files

Let's put it all together. Imagine you have a list of log files and you want to sort them by their timestamp.

Python字符串如何排序?-图3
(图片来源网络,侵删)
log_files = [
    "app_2025-10-26.log",
    "app_2025-10-25.log",
    "error_2025-10-26.log",
    "app_2025-10-24.log",
    "error_2025-10-25.log"
]
# Goal: Sort by date, newest first.
# The date is the part after the last underscore.
# We'll use a lambda to extract the date string
# The `reverse=True` is for newest first (descending order)
sorted_logs = sorted(log_files, key=lambda s: s.split('_')[-1], reverse=True)
print("Original log files:")
for log in log_files:
    print(f"  - {log}")
print("\nSorted log files (newest first):")
for log in sorted_logs:
    print(f"  - {log}")
# Output:
# Sorted log files (newest first):
#   - app_2025-10-26.log
#   - error_2025-10-26.log
#   - app_2025-10-25.log
#   - error_2025-10-25.log
#   - app_2025-10-24.log

Key Takeaways

  1. sorted() is for getting a new sorted list.
  2. .sort() is for sorting a list in-place.
  3. Use the key argument for custom sorting logic.
  4. key=str.lower is your best friend for case-insensitive sorting.
  5. key=len is perfect for sorting by length.
  6. lambda functions are great for creating simple, one-time key functions for complex rules.
分享:
扫描分享到社交APP
上一篇
下一篇