python 中的反向排序出错
reverse sorting gone wrong in python
我正在尝试创建一个脚本,它将获取一个元组,按值和名称对其进行排序——例如,如果我有:
(('apple', 5), ('tv', 500), ('bee', 1000), ('cat', 500))
我想要 return:
['bee', 'cat', 'tv', 'apple']
所以编号最大的项目排在第一位,但如果两个项目具有相同的值,则字典序较小的项目排在第一位。
这是我的代码:
def find_k_most_expensive_products(data, k):
executed_file = executeMtmikya(data)
sorted_prices_tup = sorted(executed_file[2], reverse=True, key=lambda element:
(executed_file[2][1], executed_file[2][0]))
best_sellers = []
print("------------")
print("this is the sorted prices_tup: ")
print(sorted_prices_tup)
print("------------")
for i in sorted_prices_tup:
while k > 0:
best_sellers.append(i[1])
print("k is- ")
print(k)
break
k -= 1
return best_sellers
但这是我得到的,给定:
{'apple': '5', 'tv': '500', 'bee': '1000'}
------------
this is the sorted prices_tup:
[('5', 'apple'), ('500', 'tv'), ('1000', 'bee')]
------------
k is-
3
k is-
2
k is-
1
['apple', 'tv', 'bee']
为什么它没有按预期工作?
根据提示,需要使用sorted
的key
参数。但是,您没有正确执行此操作,因为您的 lambda 不使用作为参数传递的对象。
一种方案是将数字的反义词作为第一键进行逆向排序,将单词作为第二键进行词典排序:
t = (('apple', 5), ('tv', 500), ('bee', 1000), ('cat', 500))
[x for x,_ in sorted(t, key=lambda x: (-x[1], x[0]))]
输出:['bee', 'cat', 'tv', 'apple']
尝试排序:
def sort_by_second(arr):
return sorted(arr, key=lambda x: (-1*x[1],x[0]),reverse=False)
arr = [('apple', 5), ('tv', 500), ('bee', 1000), ('cat', 500)]
print(list(map(lambda x:x[0],sort_by_second(arr))))
输出:
[bee', 'cat', 'tv', 'apple']
我正在尝试创建一个脚本,它将获取一个元组,按值和名称对其进行排序——例如,如果我有:
(('apple', 5), ('tv', 500), ('bee', 1000), ('cat', 500))
我想要 return:
['bee', 'cat', 'tv', 'apple']
所以编号最大的项目排在第一位,但如果两个项目具有相同的值,则字典序较小的项目排在第一位。 这是我的代码:
def find_k_most_expensive_products(data, k):
executed_file = executeMtmikya(data)
sorted_prices_tup = sorted(executed_file[2], reverse=True, key=lambda element:
(executed_file[2][1], executed_file[2][0]))
best_sellers = []
print("------------")
print("this is the sorted prices_tup: ")
print(sorted_prices_tup)
print("------------")
for i in sorted_prices_tup:
while k > 0:
best_sellers.append(i[1])
print("k is- ")
print(k)
break
k -= 1
return best_sellers
但这是我得到的,给定:
{'apple': '5', 'tv': '500', 'bee': '1000'}
------------
this is the sorted prices_tup:
[('5', 'apple'), ('500', 'tv'), ('1000', 'bee')]
------------
k is-
3
k is-
2
k is-
1
['apple', 'tv', 'bee']
为什么它没有按预期工作?
根据提示,需要使用sorted
的key
参数。但是,您没有正确执行此操作,因为您的 lambda 不使用作为参数传递的对象。
一种方案是将数字的反义词作为第一键进行逆向排序,将单词作为第二键进行词典排序:
t = (('apple', 5), ('tv', 500), ('bee', 1000), ('cat', 500))
[x for x,_ in sorted(t, key=lambda x: (-x[1], x[0]))]
输出:['bee', 'cat', 'tv', 'apple']
尝试排序:
def sort_by_second(arr):
return sorted(arr, key=lambda x: (-1*x[1],x[0]),reverse=False)
arr = [('apple', 5), ('tv', 500), ('bee', 1000), ('cat', 500)]
print(list(map(lambda x:x[0],sort_by_second(arr))))
输出:
[bee', 'cat', 'tv', 'apple']