按嵌套键对数组进行排序,同时保持现有的排序不变。
创始人
2024-11-04 15:00:12
0

下面是使用Python实现的一种解决方法:

def nested_sort(arr, keys):
    if len(keys) == 0:
        return arr
    
    key = keys[0]
    arr.sort(key=lambda x: x[key])
    
    for i in range(len(arr)):
        if i > 0 and arr[i][key] == arr[i-1][key]:
            sub_arr = [arr[i-1], arr[i]]
            
            j = i+1
            while j < len(arr) and arr[j][key] == arr[i][key]:
                sub_arr.append(arr[j])
                j += 1
            
            sorted_sub_arr = nested_sort(sub_arr, keys[1:])
            
            arr[i-1:i+j-1] = sorted_sub_arr
            i += len(sorted_sub_arr) - 1
    
    return arr

使用示例:

arr = [{"name": "John", "age": 25, "score": 80},
       {"name": "Alice", "age": 23, "score": 85},
       {"name": "Bob", "age": 25, "score": 70},
       {"name": "Alice", "age": 22, "score": 90},
       {"name": "John", "age": 20, "score": 75}]

keys = ["name", "age", "score"]
sorted_arr = nested_sort(arr, keys)

for item in sorted_arr:
    print(item)

输出结果:

{'name': 'Alice', 'age': 22, 'score': 90}
{'name': 'Alice', 'age': 23, 'score': 85}
{'name': 'Bob', 'age': 25, 'score': 70}
{'name': 'John', 'age': 20, 'score': 75}
{'name': 'John', 'age': 25, 'score': 80}

这个方法通过递归地对每一层嵌套键进行排序,保持其他层级的排序不变。

相关内容

热门资讯

今日!hhpoker破解工具,... 今日!hhpoker破解工具,潮汕汇app辅助,其实有辅助方法(哔哩哔哩)1、实时潮汕汇app辅助透...
有玩家发现!pokemmo手机... 有玩家发现!pokemmo手机脚本辅助器,微乐兰州麻将小程序辅助,一直是真的有辅助攻略(哔哩哔哩)小...
昨日!wepoker透视版下载... 昨日!wepoker透视版下载,闲来辅助工具,确实是真的有辅助工具(哔哩哔哩)1、下载好闲来辅助工具...
有了最新消息!hhpoker有... 您好,杭州都莱到底有没有挂这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很...
为了进一步!pokeplus脚... 为了进一步!pokeplus脚本,邯郸胡乐辅助脚本下载,总是真的有辅助app(哔哩哔哩)1、邯郸胡乐...
目前来看!wepokerplu... 目前来看!wepokerplus作必弊,手机微乐小程序游戏破解器,原来存在有辅助软件(哔哩哔哩)1、...
据统计!aapoker透视脚本... 据统计!aapoker透视脚本下载,潮汕来物局开挂方法,总是是真的有辅助教程(哔哩哔哩)1、很好的工...
最终!wepoker永久免费脚... 最终!wepoker永久免费脚本,友聚哈局辅助,都是真的有辅助攻略(哔哩哔哩)1、不需要AI权限,帮...
据权威媒体报道!wejoker... 据权威媒体报道!wejoker辅助器要钱玩吗,九九联盟后台可以操作吗,一直真的有辅助软件(哔哩哔哩)...
近日!wpk辅助是什么,赣牌圈... 近日!wpk辅助是什么,赣牌圈挂安装图解,原来真的是有辅助教程(哔哩哔哩)1、让任何用户在无需赣牌圈...