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

列表排序需求:对给定嵌套列表M执行排序操作

Hey there! Let's work through sorting this nested pyramid-style list M you've shared. Since this is a triangular nested structure, there are a few different sorting scenarios you might be aiming for—here are the most common ones with Python implementations:

1. Sort each individual row (sublist)

If you want to sort the numbers within each row (either ascending or descending), this is straightforward with list comprehensions and Python's built-in sorting functions:

Ascending order

M = [[75], [95, 64], [17, 47, 82], [18, 35, 87, 10], [20, 4, 82, 47, 65], [19, 1, 23, 75, 3, 34], [88, 2, 77, 73, 7, 63, 67], [99, 65, 4, 28, 6, 16, 70, 92], [41, 41, 26, 56, 83, 40, 80, 70, 33], [41, 48, 72, 33, 47, 32, 37, 16, 94, 29], [53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14], [70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57], [91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48], [63, 66, 4, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31], [4, 62, 98, 27, 23, 9, 70, 98, 7...]]

# Create a new sorted list without modifying the original
sorted_M_asc = [sorted(sublist) for sublist in M]

# Or modify the original list in-place
for sublist in M:
    sublist.sort()

Descending order

# Create a new list with each sublist sorted in descending order
sorted_M_desc = [sorted(sublist, reverse=True) for sublist in M]

2. Sort all elements globally, then rebuild the pyramid

If you want to sort every number in the entire structure, then put them back into the original triangular shape (same number of elements per row):

# Flatten the pyramid into a single list of numbers
all_elements = [num for row in M for num in row]
# Sort all elements (ascending by default; add reverse=True for descending)
all_elements.sort()

# Rebuild the pyramid structure
reconstructed_pyramid = []
current_index = 0
# Each row i has i+1 elements (since first row is length 1)
for row_length in range(1, len(M)+1):
    reconstructed_pyramid.append(all_elements[current_index:current_index + row_length])
    current_index += row_length

3. Sort the rows themselves (by sum, average, etc.)

If you want to reorder the entire rows based on a metric like their total sum or average value:

# Sort rows by their total sum, from largest to smallest
sorted_by_sum = sorted(M, key=lambda row: sum(row), reverse=True)

# Sort rows by their average value, from smallest to largest
sorted_by_avg = sorted(M, key=lambda row: sum(row)/len(row))

If your sorting goal is different from these (like sorting paths through the pyramid for maximum/minimum sum, for example), feel free to clarify the exact behavior you need, and I can adjust the solution!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:27:28