gpt4 book ai didi

python - 我怎样才能让元组显示每个人的总和而不是单独显示?

转载 作者:太空宇宙 更新时间:2023-11-04 02:27:41 24 4
gpt4 key购买 nike

所以我得到了这本字典,它的键是名字;它有 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)

关于python - 我怎样才能让元组显示每个人的总和而不是单独显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49962722/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com