Use PriorityQueue to get the maximum K elements
In order to sort slightly larger numbers, sometimes you don’t want all of the data, you just want the maximum k numbers up front, if you use sorted numbers ([…]). )[::-1][:k] Implementation efficiency is much lower. In order to optimize the execution speed, PriorityQueue can be used to achieve the maximum k elements. At the same time, the space can also be significantly optimized
import queue
import random
K = 12
q = queue.PriorityQueue()
tlist = []
for ith in range(100):
q.put((ith, ith + random.randrange(100)))
if q.qsize() > K: q.get() # pop least item
while not q.empty():
tnum = q.get()
tlist.append(tnum)
tlist.sort(reverse=True)
print(tlist)
The effect
[(99, 187), (98, 152), (97, 184), (96, 136),
(95, 105), (94, 119), (93, 109), (92, 169),
(91, 149), (90, 143), (89, 91), (88, 92)]
Priorityqueue are in queue bag and priorityqueue implementation in the queue is called headq inside the top of the heap, so did not provide key parameters change priority queue sorting rules, only from small to large, ascending order so, in order to get top K elements, need to queue size is greater than K pop team first element, maintain the biggest K in queue, and then use a list to undertake the element in the queue, and then descending sort results for the target at a time.
Read More:
- valueError: Length mismatch: Expected axis has 40 elements, new values have 38 elements
- Python random selects elements randomly from a collection
- for k, v in k_map: ValueError: too many values to unpack (expected 2)
- rabbit.listener.BlockingQueueConsumer$DeclarationException: Failed to declare queue(s)-2021-10-09
- Cause analysis and solution of “SVN: e155009: failed to run the WC DB work queue associated with”
- Resolve rabbitmq declarationexception: failed to declare queue exception
- Processing method of SVN error “failed to run the WC DB work queue associated with…”
- LeetCode 23. Merge k Sorted Lists(java)
- Selenium: 8 Ways to Locate Elements
- Python opencv (3) get image size
- Get picture captcha with Python + Chrome
- Several ways to center elements horizontally and vertically
- Get the current date in Python
- JQuery is a solution to the disappearance of listening events after adding elements with append
- Cisco ASA prompt modifies the display name hostname priority state context
- Solve the unmarshalling error: unexpected element (URI: “local:” name “). Expected elements are
- Remove array duplicate elements
- V-for styles individual elements
- During the development of vue, v-for reported an error [vue/require-v-for-key] Elements in iteration expect to have’v-bind:key’ directives.
- [Solved] RSA decrypt error: the data to be decrypted exceeds the maximum 128 bytes of this module