When the number of elements to be found is relatively small, functions nlargest() 和 nsmallest() 是很合适的。 如果你仅仅想查找唯一的最小或最大(N=1)的元素的话,那么使用min()和max()函数会更快些。 类似的,如果N的大小和集合大小接近的时候,通常先排序这个集合然后再使用切片操作会更快点 (sorted(items)[:N] 或者是 sorted(items)[-N:] )。 需要在正确场合使用函数nlargest() 和 nsmallest() can take advantage of them (if N is close to the size of the set, it will be better to use sorting operations).
nums = [1,2,3,2,4,5,4,3,2,1,8,9,10,11,10,9,8]
peaks = []
troughs = []
for idx in range(1, len(nums)-1):
if nums[idx-1] < nums[idx] > nums[idx+1]:
peaks.append((idx, nums[idx]))
if nums[idx-1] > nums[idx] < nums[idx+1]:
troughs.append((idx, nums[idx]))
print(peaks) # [(2, 3), (5, 5), (13, 11)]
print(troughs) # [(3, 2), (9, 1)]
First loop through to find all the peaks and troughs, and then find the top five
You can try using the
heapq
module.First loop through to find all the peaks and troughs, and then find the top five