You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中对表格按指定列进行升序与降序排序(含PrettyTable实践示例)

How to Sort PrettyTable by Any Column in Descending Order

Great question! You've already nailed ascending sorting with sortby and sort_key—let's break down a few straightforward ways to flip that to descending order for any column you want.

Method 1: Use the reverse Parameter (Simplest Approach)

PrettyTable's get_string() method has a built-in reverse parameter that lets you flip the sorted order with zero extra logic. This is the fastest way to convert an ascending sort to descending.

First, a quick correction: In your original ascending code, you used row[0] for BirthYear—but BirthYear is the second column (0-indexed, so index 1). Fixing that, here's how to sort BirthYear in descending order:

from prettytable import from_csv

with open('test.txt', 'r') as open_file:
    table_file = from_csv(open_file)

# Sort BirthYear column in descending order
print(table_file.get_string(sortby='BirthYear', sort_key=lambda row: int(row[1]), reverse=True))

You can adapt this for any column easily. For example, sorting by Name in descending alphabetical order:

print(table_file.get_string(sortby='Name', sort_key=lambda row: row[0], reverse=True))

Method 2: Reverse the Sort Key Logic

If you need more control over sorting behavior, adjust your sort_key lambda to return a reversed value. This works well for different data types:

  • For numeric columns (like BirthYear), negate the value after converting it from string to integer:
    print(table_file.get_string(sortby='BirthYear', sort_key=lambda row: -int(row[1])))
    
    Negating larger numbers makes them "smaller" in the sort, which effectively gives a descending order.
  • For string columns (like Job), you can use reversed string slices for simple descending sort, or locale-aware sorting for proper alphabetical order:
    # Simple reversed string sort for Job column
    print(table_file.get_string(sortby='Job', sort_key=lambda row: row[2][::-1]))
    
    # Locale-aware proper descending alphabetical sort (works for non-English too)
    import locale
    locale.setlocale(locale.LC_ALL, '')
    print(table_file.get_string(sortby='Job', sort_key=lambda row: locale.strxfrm(row[2]), reverse=True))
    

Method 3: Manually Sort Rows and Reconstruct the Table

For full control over the sorting process (like adding pre-sort processing), extract the table rows, sort them with Python's built-in sorted() function, then build a new PrettyTable:

from prettytable import PrettyTable, from_csv

with open('test.txt', 'r') as open_file:
    table_file = from_csv(open_file)

# Define which column to sort by (e.g., "Job")
target_column = "Job"
column_index = table_file.field_names.index(target_column)

# Sort rows in descending order (adjust key logic based on column type)
sorted_rows = sorted(
    table_file.rows,
    key=lambda row: row[column_index],
    reverse=True
)

# Build new sorted table
sorted_table = PrettyTable(table_file.field_names)
for row in sorted_rows:
    sorted_table.add_row(row)

print(sorted_table)

This method keeps your original table intact, which is handy if you need to reference unsorted data later.

内容的提问来源于stack exchange,提问作者AbdulRahman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 20:08:12