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

如何为Python数字列表生成分层排名并获取各层级索引?

解决方案

直接按以下步骤实现需求:

  1. 初始化一个和原列表长度一致的结果列表,初始值设为0
  2. 对原列表的索引按对应元素值从小到大排序,以此按元素大小顺序拿到索引序列
  3. 根据排序后的索引划分三个区间,分别为对应位置赋值排名

具体代码如下:

raw_list = [10, 9, 2, 8, 1, 3, 5, 4, 6, 7, 11]
ranked_list = [0] * len(raw_list)

# 按元素值从小到大排序索引
sorted_indices = sorted(range(len(raw_list)), key=lambda i: raw_list[i])

# 给最小的1个元素赋值排名1
ranked_list[sorted_indices[0]] = 1
# 给中间4个元素赋值排名2
for idx in sorted_indices[-10:-6]:
    ranked_list[idx] = 2
# 给最大的6个元素赋值排名3
for idx in sorted_indices[-6:]:
    ranked_list[idx] = 3

print(ranked_list)  # 输出: [3, 3, 2, 3, 1, 2, 2, 2, 3, 3, 3]

说明

  • sorted(range(len(raw_list)), key=lambda i: raw_list[i]) 生成按元素值从小到大排列的索引列表,本次示例中得到的sorted_indices为[4,2,5,7,6,9,3,1,0,8,10]
  • 切片sorted_indices[-6:]对应最大的6个元素的索引,赋值3;sorted_indices[-10:-6]对应中间4个元素的索引,赋值2;第一个索引对应最小元素,赋值1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 15:24:24