学习笔记、全局变量、闭包、过滤器、递归层数、拷贝与赋值、os函数

Pyhton笔记Day2

小知识

元组插入元素:

temp = tuple[:3] +('nihao') + tuple[3:] #插到第二个位置

del tuple #删除元组

字符串:

str = ‘i love you’str[:6]='i love'

字符串一般不修改,要修改的话就用拼接法

格式化:

“{0} love {1}.{2}”,format(“i”,“you”,“com”)

“{a} love {b}.{c}”,format(a=“i”,b=“you”,c=“com”)

“{0} love {b}.{c}”,format(“i”,b=“you”,c=“com”)

"{{0}}",format('不打印'),打印出来的是{0}

“{0:.1f}”,format(27.678),打印27.7

“%d+%d = %d”%(4,5,4+5)

函数:

	str.capitalize()第一个字符变大写
	
	str.casefold()全部变小写
	
	str.center(字节数)居中
	
	str.count()返回字符出现次数
	
	str.endwith()是否以该字符结束,返回true或者false,startswith()则相反
	
	str.expendtab(tabsize = 默认8)把字符中的\t转为空格
	
	str.find()检查字符是否在字符串中,在的话就返回索引,没有就返回-1
	
	str.istitle()首单词第一个大写 ,返回true
	
	str.jion('12345')str将12345隔开
	
	str.lstrip()去掉左边空格rstrip()右边strip(‘参数’)不填参数是去掉所有的空格,填的话去掉所有的参数
	
	str.replace(str1,str2)用2代替1
	
	str.rfind()从右边开始查找
	
	str.split()将字符串切开,按所填参数切,切开后参数不存在
	
	str.translate(str.maketrans('s','b'))将s变成b
	
	str.maketrans(‘s’,‘b’) = (115:98)

a = ‘lk x’ list(a) = [‘l’,‘k’,’ ',‘x’]

b = (1,2,3) list(b)= [1,2,3]

max()返回 参数字符串元组列表,但里面的元素要统一,同是字符或整型才可以比较

sum()参数要为数字类型,不能是字符类型,然后相加

sum(number,8)最后再加上8

sorted()排序

list(reversed())翻转

list(enumerate(number)) = [(0,1),(1,4),(2,3)]把原来的元素都变成一个元组

list(zip(a,b)打包:a = [1,2,3,4,5] b = [2,3,4] 则返回[(1,2),(2,3),(3,4)]

函数变量作用域:

def discount(price,rate):

final_price = price*rate

return final_price

old_price = float(input('请输入价格'))

rate = float(input('请输入折扣率'))

new_price = discount(ols_price,rate)

print('打折后的价格是:',new_price)

print(‘这里试图打印局部变量final_price的值',final_price)

报错:final_price没有定义
函数调用完后,就在栈中被删除了

def discount(price,rate):

final_price = price*rate

old_price = 50

print('修改后值为:', old_price)

return final_price

old_price = float(input('请输入价格'))

rate = float(input('请输入折扣率'))

new_price = discount(ols_price,rate)

print('修改后值为:', old_price)

print('打折后的价格是:',new_price)

结果后者的打印修改不成功,在函数中修改全局变量的值时,会新创建一个相同名字临时变量来修改,局部变量存放在栈里面,除了函数之后又没了,所以最终没有修改成功

global :在函数中修改全局变量前定义一次:global count
再去修改的话就行了

内嵌函数:出了所在的函数的范围就不能被调用

def fun1():
	x=5
		def fun2():
			x*=x
			return x
	return fun2()

在fun()1中定义的变量对fun2()来说是全局变量:正如fun1外部与fun1内部的关系,所以在fun2内部修改fun1的值也是无效的,以上的代码是报错的,因为在fun2中x没被定义

解决方案:将x变成一个列表。

def fun1():
	x=[5]
		def fun2():
			x[0]*=x[0]
			return x[0]
	return fun2()

或者:

def fun1():
		x=5
		def fun2():
				nonlocal x    #同global
				x*=x
				return x
		return fun2()

闭包:

		def funx(x):
			def funy(y):
					return x*y
			return funy
				
        i=funx(8)是一个函数,i(5)=40

lambda函数:省下定义的过程,使代码更加精简,用于值调用一两次的函数,不用考虑命名的问题。

lambda x:2x+1,无名字函数。调用:a=lambda x:2x+1 使用a()

a=lambda x,y:2*x+y 使用:a(x,y)

过滤器:
filter(函数参数:none,[1,0,true,false]) 返回一个对象

	list(filter(none,[1,0,true,false]))返回 [1,true]筛选出正确的部分

下面是筛选出奇数的代码:

	def odd(x):
		return x%2
	temp = range(10)
	show = filter(odd,temp)
	>>>list(show)
	>>>[1,3,5,7,9]
或者:
	>>>list(filter(lambda x:x%2,range(10)))
	>>>[1,3,5,7,9]

映射:
	>>>list(map(lambda x : x*2,range(10)))
	>>>[0,2,4,6,8,10,12,14,16,18]

递归层数:

import sys
sys.setrecursionlimit(1000)  

字典:
创建:

dict1 = dict((('F',70),('I',105)))#dict(只能写一个参数)

dictionary={键:值,键:值}   
dictionary = ['安踏':'keep moveing']

dict4['lkx']='nihaoa'          //添加键值

>>> dict3=dict(小甲鱼='让你飞',苍老师='让你走')#键不能加引号
>>> dict3
{'小甲鱼': '让你飞', '苍老师': '让你走'}

访问字典的函数:key()、values()、items()

dict.fromkeys((1,2,'哈哈'))          
{1: None, 2: None, '哈哈': None}

dict.fromkeys((1,2,'哈哈'),'number')         
{1: 'number', 2: 'number', '哈哈': 'number'}
dict.fromkeys((1,2,'哈哈'),('number','sdf','sf'))             
{1: ('number', 'sdf', 'sf'), 2: ('number', 'sdf', 'sf'), '哈哈': ('number', 'sdf', 'sf')}

dict = dict.fromkeys(range(6),'赞')    
dict          
{0: '赞', 1: '赞', 2: '赞', 3: '赞', 4: '赞', 5: '赞'}

dict.items()           
dict_items([(0, '赞'), (1, '赞'), (2, '赞'), (3, '赞'), (4, '赞'), (5, '赞')])

dict      
{0: '赞', 1: '赞', 2: '赞', 3: 'fsd', 4: '赞', 5: '赞'}          >>> dict.get(3)

拷贝与赋值的区别:

>>> a = {3,4}
>>> b=a
>>> b
{3, 4}
>>> a
{3, 4}
>>> a.clear()
>>> a
set()
>>> b
set()

拷贝:

>>> a = {3,4}
>>> b=a
>>> c=a.copy()
>>> id(a)
1650719284808
>>> id(b)
1650719284808
>>> id(c)
1650719283464

几个函数:

>>> a={3:'s',4:'d',5:'g'}
>>> a.pop(3)
's'
>>> a
{4: 'd', 5: 'g'}
>>> a.popitem()
(5	, 'g')
>>> a
{4	: 'd'}
>>> a.setdefault(5,'xiaobai')
'xiaobai'
>>> a
{4: 'd', 5: 'xiaobai'}
>>> c={7:'haha'}
>>> a.update(c)
>>> a
{4: 'd', 5: 'xiaobai', 7: 'haha'}

集合:

>>> set1 = {1,2,3,4}
>>> set1
{1, 2, 3, 4}
>>> set2 = set([1,2,3,4])#可以是列表字符串元组等
>>> set2
{1, 2, 3, 4}
>>> set2 = set('sfd')
>>> set2
{'s', 'd', 'f'}

num1.remove()
num1.add()

剔除重复的元素:

>>> num1 = [1,2,3,4,4,3,3,5,4,2,7,4]
>>> temp = []
>>> for each in num1:
if each not in temp:
	temp.append(each)	
>>> temp
[1, 2, 3, 4, 5, 7]

num1 = frozenset([1,2,3,4,5])#已经冻结
num1.add(0)#报错,不能再改了

文件:
f.open("",‘w’)不写第二个参数的话默认是r。
f.readline()读取一行
f.read()读整个文件
f.seek(0,0)
f.close()
f.writelines()写入一行
random.randint()伪随机数
os函数

os.getcwd()返回当前目录

os.chdir()修改当前目录

os.listdir()目录下的内容

os.mkdir()创建单层目录

os.redir()删除目录,目录内容要为空才行

os.remove()删除文件

os.system('calc')

os.curdir()指代上一层目录

os.pardir()指代上一层目录,os.listdir(os.pardir())如此使用才能显示

os.path.basename(‘D:\\a\\b\\c\\nihao.txt’)去掉路径,,输出nihao.txt

os.path.dirname(‘D:\\a\\b\\c\\nihao.txt’)去掉文件名,显示路径D:\\a\\b\\c

os.path.join('a','b','c')输出a\\b\\c

os.path.join('C:\\','a','b','c')

os.path.split('C:\\a\\b\\c.txt')
>>>('C:\\a\\b','c.txt')

os.path.splitext('c:\\a\\b\\c.txt')
>>>'c:\\a\\b\\c','.txt')

os.path.getatime('文件路径')返回文件最近访问时间(秒数)

time.gntime(os.path.getatime('文件路径')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值