1. 冒泡排序
def bubble_sort(lists): len_list=len(lists) for i in range(len_list): for j in range(len_list-i-1): if lists[j]>lists[j+1]: lists[j],lists[j+1]=lists[j+1],lists[j] print(lists) return lists
2. 插入排序
def insert_sort(lists): for i in range(len(lists)): position=i while position>0: if lists[position]<lists[position-1]: lists[position],lists[position-1]=lists[position-1],lists[position] position-=1 print(lists) return lists
3. 列表去重
#第一种方式 s=[1,2,6,3,1,5,2] list(set(s))
#第二种方式 l=[1,1,6,3,1,5,2] def duplictae(lists): L=[] for i in lists: if i not in L: L.append(i) return L print(duplictae(l))
4.字符串反转,例如:将string反转输出为:gnirts
#第一种方式: def str_reverse(str): return str[::-1]
#第二种方式: def str_reverse(str): L=list(str) L.reverse() new_str=''.join(L) return new_str
5.快速交换两个变量值的方法
# 方法一:通过新添加中间变量的方式,交换数值. def test(a,b): c=a a=b b=c print(a,b)
# 方法二:(此方法是Python中特有的方法) # 直接将a,b两个变量放到元组中,再通过元组按照index进行赋值的方式进行重新赋值给两个变量 def test(a,b): a,b=b,a print(a,b)
# 方法三:通过简单的逻辑运算进行将两个值进行互换 def test(a,b): a=a+b b=a-b a=a-b print(a,b) res = test(50,100)
6.删除字符串中的特殊字符,并输出指定字符串
如:str = 'welcome to shui&di',指定输出:shuidi
str = 'welcome to shui&di' new_str=str.split(' ')[2].split('&') res = ''.join(new_str)
7.在1-100之间生成一个随机数,并猜所生成的随机数值,根据猜的结果,给出正确、太大、太小的提示,如果5次均未猜对,游戏结束!
num = random.randint(1,100) for i in range(5): new_num = int(input('请输入猜测数值:')) if new_num > num: print('太大了') elif new_num < num: print('太小了') elif new_num == num: print('猜对了!') else: print('游戏结束!')
8.把字符串'ssysyysy'变成'ssssyyyy'
1 a= 'ssysyysy' 2 a_s = a.split('y') 3 s = ''.join(a_s) 4 5 a_y = a.split('s') 6 y = ''.join(a_y) 7 8 print(s+y)
分类:
python
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?