Chu*_*ong 7 python sorting floating-accuracy in-place
说我有以下清单:
my_list = [3.5, 1.6, 2.4, 8.9, 5.6]
Run Code Online (Sandbox Code Playgroud)
我想在原来的地方找到前3个最大的数字,所以结果应该是:
[3.5, 8.9, 5.6]
Run Code Online (Sandbox Code Playgroud)
我怎么能那样做?我想我可以找到 3 个最大的数字并使用过滤器,但我认为比较浮点数可能不是一个好主意。有什么建议?
使用堆:
>>> import heapq
>>> heapq.nlargest(3, my_list)
[8.9, 5.6, 3.5]
Run Code Online (Sandbox Code Playgroud)
为同一个想法添加一点修饰,以保持它们的原始顺序:
>>> from operator import itemgetter
>>> i_val = heapq.nlargest(3, enumerate(my_list), key=itemgetter(1))
>>> [val for (i, val) in sorted(i_val)]
[3.5, 8.9, 5.6]
Run Code Online (Sandbox Code Playgroud)
好了,你可以尝试一下这个功能:
my_list = [3.5, 1.6, 2.4, 5.6, 8.9]
def select_top(a,array):
new_list = []
extra_list = []
for i in range(len(my_list)):
extra_list.append(my_list[i])
final_list = []
for i in range(a):
new_list.append(extra_list.index(max(extra_list)))
extra_list.pop(extra_list.index(max(extra_list)))
new_list = sorted(new_list,reverse=False)
for i in new_list:
final_list.append(array[i])
return final_list
print(select_top(3,my_list))
Run Code Online (Sandbox Code Playgroud)
我相信这远非最佳,但您可以根据需要调整它以获得前 k 个数字并让它们按原始顺序返回。输出:
[3.5, 5.6, 8.9]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3315 次 |
| 最近记录: |