写在前面
- 以下是刷题中遇到问题时,检索到比较好的案例,
收集起来方便自己查看。 - 同时,希望也能给遇到相同问题的同学节约时间,
快速检索到解决方案。
1. map
https://www.runoob.com/python/python-func-map.html
2. collections
https://www.cnblogs.com/love9527/p/9009398.html
3. functools
https://docs.python.org/zh-cn/3/library/functools.html
4. lambda 排序 过滤
https://wenku.baidu.com/view/ffb896e2f405cc1755270722192e453610665bd7.html
5. 查找一列表中最大的数和对应索引
5.1 python内置方法
对于一个给定的列表:tmp_list = [1,2,3,4,5,6,7,9,5,4,3,3,2]
# 获取索引
tmp_list = [1,2,3,4,5,6,7,9,5,4,3,3,2]
max_index = tmp_list.index(max(tmp_list))
5.2 手动实现
def list_max(list):
#假设第一个最大,最大值的下标0
index = 0
max = list[0]
for i in range(1,len(list)):
if(list[i] > max):
max = list[i]
index = i
return (index,max)#返回多个值,使用元组
list = [99,11,33,111,55,66,88]
res = list_max(list)
print("第%d个;最大值:%d"%res)
5.3 拓展–找出第k大的数
5.3.1 思路如下:其实也就是快速排序思想
https://www.cnblogs.com/shixiangwan/p/7529980.html
https://blog.csdn.net/hackbuteer1/article/details/6651804/
https://blog.csdn.net/henusyb/article/details/88377488
python代码实现 借助内置排序方法
# 功能:找出数组中第2大的数字
def find_second_large_num(num_list):
# 找出数组中第2大的数字
# 直接排序,输出倒数第二个数即可
tmp_list = sorted(num_list)
print('Second_large_num is:', tmp_list[-2])
# 设置两个标志位一个存储最大数一个存储次大数
# two存储次大值,one存储最大值,遍历一次数组即可,先判断是否大于one,若大于将one的值给two,将num_list[i]的值给one;
# 否则比较是否大于two,若大于直接将num_list[i]的值给two;否则pass
one = num_list[0]
two = num_list[0]
for i in range(1, len(num_list)):
if num_list[i] > one:
two = one
one = num_list[i]
elif num_list[i] > two:
two = num_list[i]
else:
pass
print('Second_large_num is:', two)
print(num_list.index(two))
if __name__ == '__main__':
num_list = [34, 11, 23, 56, 78, 0, 9, 12, 3, 7, 5]
find_second_large_num(num_list)
5.3.2 快排思想
def find_k_quick_sorted(container, start, end, k):
if k < 0 or container == [] or start < 0 or end >= len(container) or k > end:
return None
low = start
high = end
key = container[start]
while low < high:
while low < high and container[high] >= key:
high -= 1
container[low] = container[high]
while low < high and container[low] <= key:
low += 1
container[high] = container[low]
container[low] = key
if low < k:
return find_k_quick_sorted(container, start + 1, end, k)
elif low > k:
return find_k_quick_sorted(container, start, end - 1, k)
else:
return container[low]
container = [3, 5, 6, 7, 2, -1, 9, 3]
print(sorted(container))
print(find_k_quick_sorted(container, 0, len(container) - 1, 5))
6. filter
- filter需要传入两个参数 第一个参数时函数,第二参数时可迭代对象
- 通常搭配匿名函数lambda使用
total = [" ", " ", 2]
# str(x).isdigit() 判断字符串是否为纯数字
new_total = list(filter(lambda x: str(x).isdigit(), total))
print(new_total)
详细见链接
写在最后
- 学习ing,工作ing,持续更新。。。
- 此页面只做快速导航