所以我得到了这本字典,它的键是名字;它有 3 个值的元组:在 3 元组中,股票名称、该交易的交易股票数量 (int) 和每股价格 (int)。
new_dict = {
'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)]
}
我正在创建一个函数,该函数返回一个二元组列表作为结果(客户,以及他们出售(负数)或购买(正数)的股票总数的绝对值。 - 该列表根据他们交易的股票数量的总和按降序排列;如果两个客户交易的股票数量相同,则他们必须按字母顺序递增。
对于 new_dict 作为字典,输出应该是 [('Alan', 120), ('Dawn', 120), ('Barb', 80), ('Carl', 80)]
这是我所做的:
def most_active_clients(database :{str: (str, int, int)}) -> list:
result = []
t = list()
for key,val in database.items():
for x in val:
t.append((key,abs(x[1])))
for item in t:
print(item)
我似乎无法弄清楚如何获得所有 x[1] 的总和然后对其进行排序。有人可以帮助我吗?
请您参考如下方法:
使用排序方法
new_dict = {
'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)]
}
def most_active_clients(new_dict):
res = []
for k, v in new_dict.items():
name = k
sum = 0
for l in v:
sum += abs(l[1])
res.append((name, sum))
return sorted(res, key=lambda x: (-x[1], x[0]), reverse=False)
print(most_active_clients(new_dict))
我已经按照我认为简单的方式实现了。
你需要的行是
return sorted(res, key=lambda x: (-x[1], x[0]), reverse=False)
