当前位置: 首页 > news >正文

python数据结构和字符串用法

python数据结构和字符串用法

#Python 中数学运算常用的函数基本都在 math 模块
import math
print(math.ceil(4.1)) #5
print(math.floor(4.9)) #4
print(math.fabs(-10)) #10.0
print(math.sqrt(9)) #3.0
print(math.exp(1)) #2.718281828459045

#Python随机数
#使用random()方法即可随机生成一个[0,1)范围内的实数
import random
ran=random.random()
print(ran)

#randint()生成一个随机整数
ran=random.randint(1,20)
print(ran)

#字符串
#字符串连接:+
a="Hello "
b="World "
print(a+b)

#重复输出字符串:*
print(a*3)

#通过索引获取字符串中字符[]
print(a[0]) #H

#字符串截取[:] 牢记:左闭右开
print(a[1:4]) #ell

#判断字符串中是否包含给定的字符: in, not in
print(‘e’ in a) #True
print(‘e’ not in a) #False

#join():以字符作为分隔符,将字符串中所有的元素合并为一个新的字符串
new_str=‘-’.join(‘Hello’)
print(new_str)

#字符串单引号、双引号、三引号
print(‘Hello World!’)
print(“Hello World!”)

#转义字符
print(“The \t is a tab”)
print(‘I’m going to the movies’)

#引号让程序员从引号和特殊字符串的泥潭里面解脱出来,自始至终保持一小块字符串的格式是所谓的WYSIWYG(所见即所得)格式的。
print(‘’‘I’m going to the movies’‘’)

html = ‘’’

Friends CGI Demo

ERROR

%s

''' print(html)

#声明一个列表,并通过下标或索引获取元素
names=[‘jack’,‘tom’,‘tonney’,‘superman’,‘jay’]
#通过下标或索引获取元素
print(names[0])
print(names[1])

##获取最后一个元素
print(names[-1])
print(names[len(names)-1])
#获取第一个元素
print(names[-5])

#遍历列表,获取元素
for name in names:
print(name)

#查询names里面有没有superman
for name in names:
if name==‘superman’:
print(‘有超人’)
break
else:
print(‘无超人’)

#更简单的方法,来查询names里有没有superman
if ‘superman’ in names:
print(‘有超人’)
else:
print(‘无超人’)

#列表元素添加
#声明一个空列表
girls=[]
girls.append(‘small tom’)
print(girls)

#extend(),一次添加多个。把一个列表添加到另一个列表 ,列表合并。
models=[‘big sister’,‘middle sister’]
girls.extend(models)
#girls=girls+models OK
print(girls)

#insert():指定位置添加
girls.insert(1,‘书欣’)
print(girls)

#列表元素修改,通过下标找到元素,然后用=赋值
fruits=[‘apple’,‘pear’,‘banana’,‘pineapple’,‘caomei’]
print(fruits)

fruits[-1]=‘strawberry’
print(fruits)

#将fruits列表中的‘banana’替换为’香蕉’

no modify

for fruit in fruits:
if ‘banana’ in fruit:
fruit=‘香蕉’
print(fruits)

#OK update banana->香蕉
for i in range(len(fruits)):
if ‘banana’ in fruits[i]:
fruits[i]=‘香蕉’
break
print(fruits)

#列表元素删除
words=[‘cat’,‘hello’,‘pen’,‘pencil’,‘ruler’]
del words[0]
print(words)

words.remove(‘pen’)
print(words)

words.pop(0)
print(words)

#列表切片
#在Python中处理列表的部分元素,称之为切片。
#创建切片,可指定要使用的第一个元素和最后一个元素的索引。注意:左闭右开
#将截取的结果再次存放在一个列表中,所以还是返回列表
animals = [‘cat’,‘dog’,‘tiger’,‘snake’,‘mouse’,‘bird’]
print(animals[2:5]) #[‘tiger’, ‘snake’, ‘mouse’]
print(animals[-1:]) #[‘bird’]
print(animals[-3:-1]) #[‘snake’, ‘mouse’]
print(animals[-5👎2]) #[‘dog’, ‘snake’]
print(animals[::2]) #[‘cat’, ‘tiger’, ‘mouse’]

#列表排序
import random
random_list=[]
for i in range(10):
ran=random.randint(1,20)
if(ran not in random_list):
random_list.append(ran)
print(random_list) #少项数<10 [11, 5, 9, 1, 10, 20, 12, 2]

random_list=[]
i=0
while i<10:
ran=random.randint(1,20)
if(ran not in random_list):
random_list.append(ran)
i+=1
print(random_list) #[8, 11, 2, 10, 6, 19, 16, 3, 17, 7]

#默认升序 排序
new_list=sorted(random_list)
print(new_list)

#降序 排序
new_list=sorted(random_list,reverse=True)
print(new_list)

#元组 与列表类似,元组中的内容不可修改
tuple1=()
print(type(tuple1)) #<class ‘tuple’>

tuple2=(‘hello’)
print(type(tuple2)) #<class ‘str’>

#注意:元组中只有一个元素时,需要在后面加逗号!
tuple3=(‘hello’,)
print(type(tuple3))

#元组不能修改,所以不存在往元组里加入元素。
#那作为容器的元组,如何存放元素?
random_list = []
for i in range(10):
ran = random.randint(1,20)
random_list.append(ran)
print(random_list)

random_tuple = tuple(random_list)
print(random_tuple)

#元组访问
print(random_tuple[0])
print(random_tuple[-1])
print(random_tuple[1:-3])
print(random_tuple[::-1])

#元组的修改:
t1=(1,2,3)+(4,5)
print(t1) #(1, 2, 3, 4, 5)

t2=(1,2)*2
print(t2) #(1, 2, 1, 2)

#元组的一些函数:
print(max(random_tuple))
print(min(random_tuple))
print(sum(random_tuple))
print(len(random_tuple))

#字典
#定义一个空字典
dict1={}
dict2={‘name’:‘tom’,‘weight’:45,‘age’:25}
print(dict2[‘name’])

#list可以转成字典,但前提是列表中元素都要成对出现
dict3 = dict([(‘name’,‘杨超越’),(‘weight’,45)])
print(dict3)

dict4 = {}
dict4[‘name’] = ‘虞书欣’
dict4[‘weight’] = 43
print(dict4)

dict4[‘weight’] = 44
print(dict4)

#字典里的函数 items() keys() values()
dict5 = {‘杨超越’:165,‘虞书欣’:166,‘上官喜爱’:164}
print(dict5.items())
for key,value in dict5.items():
if value > 165:
print(key)

#values() 取出字典中所有的值,保存到列表中
results = dict5.values()
print(results)

#求小姐姐的平均身高
heights = dict5.values()
print(heights)
total = sum(heights)
avg = total/len(heights)
print(avg)

names = dict5.keys()
print(names)

#字典获取用法
#print(dict5[‘赵小棠’]) #若不存在“赵小棠”,会报错KeyError
print(dict5.get(‘赵小棠’))
print(dict5.get(‘赵小棠’,170)) #如果能够取到值,则返回字典中的值,否则返回默认值170

#字典删除用法
dict6 = {‘杨超越’:165,‘虞书欣’:166,‘上官喜爱’:164}
del dict6[‘杨超越’]
print(dict6)

result = dict6.pop(‘虞书欣’)
print(result)
print(dict6)
#—the—end—字符串

http://www.lryc.cn/news/97861.html

相关文章:

  • ext4 - mballoc块分配机制
  • Spring整合junit
  • Swift 让ScrollView滚动到具体某个位置
  • 【C语言day08】
  • 【并发编程】ThreadLocal
  • 如何提高自己的软件测试水平之bug定位
  • 发点实用的快捷键(mac
  • Android播放多媒体文件——播放音频
  • 存储重启后,ceph挂载信息没了,手动定位osd序号并挂载到对应磁盘操作流程、ceph查看不到osd信息处理方法
  • Linux学习之循环处理位置参数
  • NLP实战8:图解 Transformer笔记
  • Pytorch个人学习记录总结 玩俄罗斯方块の深度学习小项目
  • PuTTY连接服务器报错Connection refused
  • 11-3_Qt 5.9 C++开发指南_QSqlQuery的使用(QSqlQuery 是能执行任意 SQL 语句的类)
  • 神码ai火车头伪原创插件怎么用【php源码】
  • 13.Netty源码之Netty中的类与API
  • C# 如何检查数组列表中是否存在数组
  • AI课堂教学质量评估系统算法 yolov7
  • eventBus使用遇到的坑
  • ChatGPT应用|科大讯飞星火杯认知大模型场景创新赛开始报名了!
  • DM8 DSC备份还原
  • 【Docker--harbor私有仓库部署与管理】
  • 基于量子同态加密的安全多方凸包协议
  • MySQL案例——多表查询以及嵌套查询
  • AI 视频清晰化CodeFormer-Deepfacelab
  • TCP协议如何实现可靠传输
  • 万恶的Eclipse的使用
  • 文件上传--题目
  • 小程序创建
  • stable diffusion如何确保每张图的面部一致?