python实战小案例(基础操作、基础算法、列表、字典、集合)
2020-06-10 04:39
781 查看
文章目录
- 1、打印乘法表
- 2、 嵌套数组完全展开
- 3、 将list等分为子组
- 4、 生成fibonacci序列前n项
- 5 、过滤掉各种空值
- 7、 返回列表尾元素
- 8 、对象转换为可迭代类型
- 9 、求更长列表
- 10、 出现最多元素
- 11、求多个列表的最大值
- 12、 求多个列表的最小值
- 13、 检查list是否有重复元素
- 14、 求列表中所有重复元素
- 15、 列表反转
- 16、 浮点数等差数列
在此之前学完python基础的同学推荐实操一下简单案例
https://www.runoob.com/python/python-100-examples.html【菜鸟教程100个小案例】
https://www.runoob.com/python3/python3-examples.html【菜鸟教程算术实例】
一、基础操作
1 、链式比较
i = 3 print(1 < i < 3) # False print(1 < i <= 3) # True
2 、不用else和if实现计算器
from operator import * def calculator(a, b, k): return { '+': add, '-': sub, '*': mul, '/': truediv, '**': pow }[k](a, b) calculator(1, 2, '+') # 3 calculator(3, 4, '**') # 81
3 、函数链
from operator import (add, sub) def add_or_sub(a, b, oper): return (add if oper == '+' else sub)(a, b) add_or_sub(1, 2, '-') # -1
4 、求字符串的字节长度
def str_byte_len(mystr): return (len(mystr.encode('utf-8'))) str_byte_len('i love python') # 13(个字节) str_byte_len('字符') # 6(个字节)
5 、寻找第n次出现位置
def search_n(s, c, n): size = 0 for i, x in enumerate(s): if x == c: size += 1 if size == n: return i return -1 print(search_n("fdasadfadf", "a", 3))# 结果为7,正确 print(search_n("fdasadfadf", "a", 30))# 结果为-1,正确
6 、去掉最高最低求平均
def score_mean(lst): lst.sort() lst2=lst[1:(len(lst)-1)] return round((sum(lst2)/len(lst2)),2) score_mean([9.1, 9.0,8.1, 9.7, 19,8.2, 8.6,9.8]) # 9.07
7 、交换元素
def swap(a, b): return b, a swap(1, 0) # (0,1)
二、基础算法
1 、二分搜索
def binarySearch(arr, left, right, x): while left <= right: mid = int(left + (right - left) / 2); # 找到中间位置。求中点写成(left+right)/2更容易溢出,所以不建议这样写 # 检查x是否出现在位置mid if arr[mid] == x: print('found %d 在索引位置%d 处' %(x,mid)) return mid # 假如x更大,则不可能出现在左半部分 elif arr[mid] < x: left = mid + 1 #搜索区间变为[mid+1,right] print('区间缩小为[%d,%d]' %(mid+1,right)) elif x<arr[mid]: right = mid - 1 #搜索区间变为[left,mid-1] print('区间缩小为[%d,%d]' %(left,mid-1)) return -1
2 、距离矩阵
x,y = mgrid[0:5,0:5] list(map(lambda xe,ye: [(ex,ey) for ex, ey in zip(xe, ye)], x,y)) [[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4)], [(1, 0), (1, 1), (1, 2), (1, 3), (1, 4)], [(2, 0), (2, 1), (2, 2), (2, 3), (2, 4)], [(3, 0), (3, 1), (3, 2), (3, 3), (3, 4)], [(4, 0), (4, 1), (4, 2), (4, 3), (4, 4)]]
三、列表
1、打印乘法表
for i in range(1,10): for j in range(1,i+1): print('{0}*{1}={2}'.format(j,i,j*i),end="\t") print() 结果: 1*1=1 1*2=2 2*2=4 1*3=3 2*3=6 3*3=9 1*4=4 2*4=8 3*4=12 4*4=16 1*5=5 2*5=10 3*5=15 4*5=20 5*5=25 1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36 1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49 1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64 1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81
2、 嵌套数组完全展开
from collections.abc import * def flatten(input_arr, output_arr=None): if output_arr is None: output_arr = [] for ele in input_arr: if isinstance(ele, Iterable): # 判断ele是否可迭代 flatten(ele, output_arr) # 尾数递归 else: output_arr.append(ele) # 产生结果 return output_arr flatten([[1,2,3],[4,5]], [6,7]) # [6, 7, 1, 2, 3, 4, 5]
3、 将list等分为子组
from math import ceil def divide(lst, size): if size <= 0: return [lst] return [lst[i * size:(i+1)*size] for i in range(0, ceil(len(lst) / size))] r = divide([1, 3, 5, 7, 9], 2) # [[1, 3], [5, 7], [9]]
4、 生成fibonacci序列前n项
def fibonacci(n): if n <= 1: return [1] fib = [1, 1] while len(fib) < n: fib.append(fib[len(fib) - 1] + fib[len(fib) - 2]) return fib fibonacci(5) # [1, 1, 2, 3, 5]
5 、过滤掉各种空值
def filter_false(lst): return list(filter(bool, lst)) filter_false([None, 0, False, '', [], 'ok', [1, 2]])# ['ok', [1, 2]] 6 返回列表头元素 def head(lst): return lst[0] if len(lst) > 0 else None head([]) # None head([3, 4, 1]) # 3
7、 返回列表尾元素
def tail(lst): return lst[-1] if len(lst) > 0 else None print(tail([])) # None print(tail([3, 4, 1])) # 1
8 、对象转换为可迭代类型
from collections.abc import Iterable def cast_iterable(val): return val if isinstance(val, Iterable) else [val] cast_iterable('foo')# foo cast_iterable(12)# [12] cast_iterable({'foo': 12})# {'foo': 12}
9 、求更长列表
def max_length(*lst): return max(*lst, key=lambda v: len(v)) r = max_length([1, 2, 3], [4, 5, 6, 7], [8])# [4, 5, 6, 7]
10、 出现最多元素
def max_frequency(lst): return max(lst, default='列表为空', key=lambda v: lst.count(v)) lst = [1, 3, 3, 2, 1, 1, 2] max_frequency(lst) # 1
11、求多个列表的最大值
def max_lists(*lst): return max(max(*lst, key=lambda v: max(v))) max_lists([1, 2, 3], [6, 7, 8], [4, 5]) # 8
12、 求多个列表的最小值
def min_lists(*lst): return min(min(*lst, key=lambda v: max(v))) min_lists([1, 2, 3], [6, 7, 8], [4, 5]) # 1
13、 检查list是否有重复元素
def has_duplicates(lst): return len(lst) == len(set(lst)) x = [1, 1, 2, 2, 3, 2, 3, 4, 5, 6] y = [1, 2, 3, 4, 5] has_duplicates(x) # False has_duplicates(y) # True
14、 求列表中所有重复元素
from collections import Counter def find_all_duplicates(lst): c = Counter(lst) return list(filter(lambda k: c[k] > 1, c)) find_all_duplicates([1, 2, 2, 3, 3, 3]) # [2,3]
15、 列表反转
def reverse(lst): return lst[::-1] reverse([1, -2, 3, 4, 1, 2])# [2, 1, 4, 3, -2, 1]
16、 浮点数等差数列
def rang(start, stop, n): start,stop,n = float('%.2f' % start), float('%.2f' % stop),int('%.d' % n) step = (stop-start)/n lst = [start] while n > 0: start,n = start+step,n-1 lst.append(round((start), 2)) return lst rang(1, 8, 10) # [1.0, 1.7, 2.4, 3.1, 3.8, 4.5, 5.2, 5.9, 6.6, 7.3, 8.0]
四、字典
1 、字典值最大的键值对列表
def max_pairs(dic): if len(dic) == 0: return dic max_val = max(map(lambda v: v[1], dic.items())) return [item for item in dic.items() if item[1] == max_val] max_pairs({'a': -10, 'b': 5, 'c': 3, 'd': 5})# [('b', 5), ('d', 5)]
2、 字典值最小的键值对列表
def min_pairs(dic): if len(dic) == 0: return [] min_val = min(map(lambda v: v[1], dic.items())) return [item for item in dic.items() if item[1] == min_val] min_pairs({}) # [] r = min_pairs({'a': -10, 'b': 5, 'c': 3, 'd': 5}) print(r) # [('b', 5), ('d', 5)]
3、 合并两个字典
def merge_dict2(dic1, dic2): return {**dic1, **dic2} # python3.5后支持的一行代码实现合并字典 merge_dict({'a': 1, 'b': 2}, {'c': 3}) # {'a': 1, 'b': 2, 'c': 3} 4 求字典前n个最大值 from heapq import nlargest # 返回字典d前n个最大值对应的键 def topn_dict(d, n): return nlargest(n, d, key=lambda k: d[k]) topn_dict({'a': 10, 'b': 8, 'c': 9, 'd': 10}, 3) # ['a', 'd', 'c']
5、 求最小键值对
d={'a':-10,'b':5, 'c':3,'d':5} min(d.items(),key=lambda x:x[1]) #('a', -10)
五、集合
1 、互为变位词
from collections import Counter # 检查两个字符串是否 相同字母异序词,简称:互为变位词 def anagram(str1, str2): return Counter(str1) == Counter(str2) anagram('eleven+two', 'twelve+one') # True 这是一对神器的变位词 anagram('eleven', 'twelve') # False
相关文章推荐
- python基础 第一天 (列表操作、字典操作,集合操作,文件操作)
- Python基础:列表,元组,字典,集合相关基本操作
- Python基础操作 列表 字典结构 集合 循环 判断 复制操作 函数
- [置顶] Python联系笔记2[列表,元组,集合,字典,函数,文件操作,模块,类]
- Python基础2 列表、字典、集合
- python入门:基础,列表、元组、字典及集合类型
- python基础2(列表,元组,字典,集合,运算符)
- Python 入门学习 -----变量及基础类型(元组,列表,字典,集合)
- python字典与集合 基础操作
- python基础总结——列表元组集合字典文件等等
- python基础语法实验_列表、集合、元组、字典
- python基础数据结构——列表(list), 元祖(tuple), 字典(dict), 字符串(string), 集合(set) 介绍及相互转换
- 兄弟连学python(02)——python 基础知识 列表、字典、元组、集合
- Python基础【数据结构:列表 | 元组 | 集合 | 字典】
- 2.python基础知识(分支循环、列表、元组、字典、集合、函数)
- Python 基础之集合相关操作与函数和字典相关函数
- Python基础(三)Python容器:列表、元组、字典和集合
- Python基础-列表_元组_字典_集合
- Python_基础语法_组合数据类型_列表_元组_字典_集合(4)
- 【Python】基础学习——列表(list),元祖(tuple),字典(dict),字符串(string),集合(set)