Python模块:heapq
概述
首先明确,heapq模块是可以用来求前n个最大/最小值的(怎么样,是不是很常见的应用场景)
通常在Python中,求前n个最大/最小值的方法无非是通过排序,它通常和列表相联系
#之前的办法 借用排序
lyst = [-3, 22, 45, 34, 99, 102, -44]
low3 = sorted(lyst)[:3]
print(low3)
top3 = sorted(lyst, reverse=True)[:3]
print(top3)
[-44, -3, 22]
[102, 99, 45]
#调用heapq模块后
import heapq
lyst = [-3, 22, 45, 34, 99, 102, -44]
low3 = heapq.nlargest(3, lyst)
top3 = heapq.nsmallest(3, lyst)
print(low3)
print(top3)
[102, 99, 45]
[-44, -3, 22]
主要函数介绍
nlargest()、nsmallest()函数接受两个参数,第一个是前n大/小的n的具体值,第二个是可迭代序列(列表、元组、字符串)
就这样
heapq.nlargest(3, lyst)
Python map() 函数
描述
map() 会根据提供的函数对指定序列做映射。
第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。
语法
map() 函数语法:
map(function, iterable, …)
def square(x):
return x**2
list(map(square,[1,2,3,4,5]))
[1, 4, 9, 16, 25]
list(map(lambda x: x**2,[1,2,3,4,5])) #lambda 匿名函数
[1, 4, 9, 16, 25]
list(map(lambda x,y: x+y , [1,3,5,7,9],[2,4,6,8,10]))
[3, 7, 11, 15, 19]
python返回数组的索引
nums = [1, 2, 3, 4, 5, 6, 1, 9]
print(nums.index(1)) #只返回第一个索引值
print(nums[::-1].index(2)) #取从后向前(相反)的元素
print(nums.index(max(nums))) #9 index
#用这种方法可以判断某个元素在数组或字符串中是否只出现一次。
#正序index + 逆序index = 数组或者字符串的长度-1
0
6
7
#同样适用于字符串
str1 = 'abcd'
print(str1.index('c'))
2
nums = [1, 2, 3, 4, 5, 6, 1, 9]
print(nums[::-1])
[9, 1, 6, 5, 4, 3, 2, 1]