所以我得到了这个字典,其中的键是名字;它具有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)]
}
我正在创建一个函数,该函数返回一个2元组的列表(客户端,它们销售的股票数量(负数)或买入(正数)总数的绝对值。 - 根据交易的股票数量总和,按递减顺序对列表进行排序;如果两个客户交易相同数量的股票,则必须按字母顺序增加。
对于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]的总和,然后对其进行排序。有人能帮助我吗?
答案 0 :(得分: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)
答案 1 :(得分:1)
分2步:
以下是代码:
abs_shares = {(key, sum(abs(x[1]) for x in val)) for key, val in new_dict.items()}
print(sorted(abs_shares, key=lambda x: (-x[1], x[0])))
输出符合预期:[('Alan', 120), ('Dawn', 120), ('Barb', 80), ('Carl', 80)]
答案 2 :(得分:0)
这是获得结果的一种方式:
database = {
'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)]
}
t = []
for key, val in database.items():
for x in val:
t.append((key,abs(x[1])))
a_set = {x[0] for x in t}
res = sorted([(i,sum(x[1] for x in t if x[0] == i)) for i in a_set], key=lambda x: x[1], reverse=True)
print(res)
# [('Alan', 120), ('Dawn', 120), ('Barb', 80), ('Carl', 80)]