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

Python按值长度及字母序排序字典并实现高频交易者函数

Solution to Sort Frequent Traders

Let's tackle this problem step by step. The goal is to return a list of client names sorted first by how many transactions they've made (more frequent traders come first), then alphabetically by name if two clients have the same number of transactions.

Here's the complete, polished implementation of the frequent_traders function:

def frequent_traders(db: {str: [(str, int, int)]}) -> [str]:
    # Sort by transaction count (descending), then by client name (ascending)
    return sorted(db, key=lambda user: (-len(db[user]), user))

Breakdown of the Logic:

  • The sorted() function iterates over the dictionary's keys (which are the client names).
  • The key parameter uses a lambda function to create a sort tuple for each user:
    • -len(db[user]): We negate the length of the user's transaction list to sort from most transactions to least (since sorted() defaults to ascending order, adding the negative flips it to descending).
    • user: This is the secondary sort key—when two users have the same number of transactions, they'll be ordered alphabetically from A to Z.

Testing with Your Sample Data

Using your provided db dictionary:

db = {
    'Carl': [('Intel', 30, 40), ('Dell', 20, 50), ('Intel', -10, 60), ('Apple', 20, 55)],
    'Barb': [('Intel', 20, 40), ('Intel', -10, 45), ('IBM', 40, 30), ('Intel', -10, 35)],
    'Alan': [('Intel', 20, 10), ('Dell', 10, 50), ('Apple', 80, 80), ('Dell', -10, 55)],
    'Dawn': [('Apple', 40, 80), ('Apple', 40, 85), ('Apple', -40, 90)]
}

Calling frequent_traders(db) will return:

['Alan', 'Barb', 'Carl', 'Dawn']

This aligns perfectly with the requirements: Alan, Barb, and Carl all have 4 transactions (sorted alphabetically), followed by Dawn with 3 transactions.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:29:21