1.输出语句
title=r'tzy\'\t577' #字符串双引号/单引号前面加上r表示字符串原样输出
print(title)
money_all = 1.2+.31+ 4654
print(int(money_all),str(money_all))
print(hex(100),oct(100))
print(-36%5)
#取余运算,结果符号和后者一致,单/结果为浮点数,//结果为整数
print(36%-5,-36%-5,-36%5,36/5,36//5)
(n)=input("please enter the n:")
a=1
b=2
print(a<b)
print(0 < int(n) < 50) #python可以连续比较大小
2.枚举类型的使用方法
from enum import Enum
class Week(Enum):
星期一 = 1
星期二 = 2
星期三 = 3
星期四 = 4
星期五 = 5
星期六 = 6
星期天 = 7
flag=0
day=input("please enter the day:")
time = int(input("please enter the time:"))
if time < 0 or time > 24:
print("输入了错误的时间!")
else:
for temp in Week.__members__:
if(temp == day):
flag=1
if flag == 1:
if(((day == "星期天" and 12<time<18)
or (day == "星期一" and 8<time<12))):
print("you got the service!")
else:
print("thank you for your partipation!")
else:
print("请输入正确的星期格式!")
#遍历星期还可以用enumerate
week = ["星期一","星期二","星期三","星期四","星期五","星期六","星期天"]
for i,element in enumerate(week,start=1): #对于week函数从start=1开始记录下标
print(i,element)
3.位运算
#**默认以8位补码存储数据**
a=10
b=7
print(a&b,a|b,a^b,~a,a>>1,a<<1)
print(hex(3 + 4 & 5 + 5))
if a>1:
print("小于10")
else:
print("大于10")
4.列表的使用和元组
num=["1","2","3","4","5","6","7","8","9",0]
print(num[:]) #从第二个元素开始,到5-1个元素
#列表相加类型需要一致:列表+列表,元组+元组,字符串+字符串
num1 = [1,2,3,4,5,6,7,8,9,0]
num2 = [100,200,"300"] #内有字符串,但是num2是一个列表
print(num2*3) #序列乘法表示将序列内的内容重复多次
print(num2+num1) #序列加法是按加的先后顺序链接起两个序列
print(num[0:9:2]) #步长为2,从0号元素输出到9号
print(num[:]) #表示全部输出
print(num[5:]) #表示从5号元素(6)开始全部输出
print(num[:5]) #表示从0号元素开始,输出到4号元素
empty=[None]*5 #对于None的乘法要乘在括号外面
print(empty)
print(" "*5) #有内容可以在括号内乘法,重复某一个字符串
str = "*"*5 #可以一开始就定义五个字符串
print(str)
print("1" in num2) #元素 in 列表,查询某个元素
print(len(num1),max(num1),min(num1),sum(num1)) #len函数计算的是字符数,无论是英文还是中文
tuple_1=(4,2,3)
#tuple_1[0]=100
List_1 = list(tuple_1)
List_1[0] =100
rtuple_1=list(reversed(tuple_1)) #reversed可以用于元组,列表,字符串。反转后还要强制转换成list类型
rList_1=list(reversed(List_1))
print(List_1,sorted(tuple_1),sorted(List_1),rtuple_1,rList_1)
#enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
#这些函数的返回值是返回序列seq的反向访问的迭代器,需要强制转换成列表List
print(list(enumerate(num1,start=1))) #下标从1开始
for i,element in enumerate(num1,start=1):
print(i,element)
print(list(range(2,21,2))) #range函数从2开始到21-1位置,步数为2
str = "ustc_tzy"
print(list("ustc_tzy"),list(str))
for index,element in enumerate(str):
if(index % 2 == 0):
print(index+1,element+"\t\t",end='') #end=''表示不换行
else:
print(index+1,element+"\n")
del str #删除str
import datetime #导入日期时间了
day = datetime.datetime.now().weekday() #获取日期,now是时间,weekday是星期,返回0-6
print(day)
def fun(a,b):
"返回多个值,结果以元组形式表示"
return "tzy","lss"
print(type(fun(1,2)))
#Python的元组与列表类似,元组使用小括号,列表使用方括号。
empty_tuple = () #空元组
tuple_ = (1,1,2,3,4)
print(tuple_)
# tuple_[0] = 2 #元组中的函数不能修改 TypeError: 'tuple' object does not support item assignment
#元组中只包含一个元素时,需要在元素后面添加逗号,不然不能知道到底是一个数还是元组
tup1 = (50,)
5.列表操作和函数
#**修改列表**
#1.增加:
temp=["1","2","3","4"]
seq=[1,2,3]
print(len(temp),temp)
temp.append("5")
print(temp)
temp.insert(1,"-1") #在索引为1添加元素,insert效率低于append
print(temp)
temp.extend(seq) #将seq添加到temp后面
print(temp)
#2.修改:
temp[0]=100
print(temp)
#2.删除:
del temp[0] #由索引删除元素,需要已知位置
print(temp)
temp1=[1,1,2,3,4]
print(temp1)
if 5 in temp1: #最好先判断需要删除元素是否在列表中
temp1.remove(5) #根据值删除,但只会删除一个
print(temp1)
#**列表内置函数**
temp = [1,1,1,2,3,6,5,7]
print(temp.count(1)) #获取元素在列表中的个数
if 1 in temp: #最好判断是否存在
print(temp.index(1)) #获得元素第一次出现的位置
print(sum(temp,1000)) #对列表求和并有一个基准值1000,即求和后加1000
#排序(列表内置函数sort(),python内置函数sorted)
#默认升序,sorted函数排序后不会改变列表的顺序
#temp.sort(reverse=True)
temp1=sorted(temp,reverse=True)
print(temp,temp1) #不会改变temp值,temp1才改变了
str1 = ["A","b","C","D"]
str1.sort(key = str.lower) #字符串按照的是先大写排序,key = str.lower()使得不按照大小写区分
print(str1)
#列表推导式 list = [Expression for var in range] Expression是写入列表的数据所要遵守的规则
#**列表推导式**
list = [i*i for i in range(2,11,2)]
print(list) #表达式+按一定条件循环
import random
random_list = [random.randint(0,100) for i in range(0,10)]
print(random_list)
#i是变量,会依次加一(个元素或者值);range是变量的取值范围
#上面获取随机数的方法是列表推导式,
temp=[]
for i in range(10):
temp.append(random.randint(0,100))
print(temp)
#newlist = [Expression for var in list]
#对于price内所有元素,按照顺序,将每个元素打折后写入sale中
price = [1000,8000,600,888]
sale = [float(i*0.7) for i in price]
print(price,sale)
#newlist = [Expression for var in range if condition]
#列表推导式还可以先在某个列表中选择部分元素,再按给出的表达式处理元素后放入新的列表
#在price列表中,选择价格大于1000的打7折
sale1 =[int(i*0.7) for i in price if i>1000]
print(sale1)
6.类的定义和基本使用
def foo(debug = True):
'this is the info about the function' #在函数或者类型定义的下面可以用单引号或者双引号定义一句文本说明类的帮助信息
if debug:
print("you need debug now!")
else:
print("the code is ok!")
print(foo.__doc__)
#可以用ctrl+c退出当前的无限循环(在idle中),在pycharm中是ctrl+F2
while 1:
print(1)
#类的定义和类中数据的类型
class Student(object):
"学生类"
def __init__(self,name,score):
self.name = name
self.score = score
stu = Student("tzy",100)
print(stu.name,stu.score,stu)
print(type(stu.name),type(stu),type(Student),Student)
print(stu.__doc__,Student.__base__)
class Animal:
''class animal''
num = 0
def __init__(self,name,color): #初始类
''certain animal'' #只要是字符串就行,单/双/三引号都可以
self.name = name
self.color = color
print("create a animal")
def get_name(self): #可以不让别人调用里面的变量,将数据封装
return self.name,self.color
lion = Animal("lion","yellow")
print(lion.get_name())
print(dir(Animal),end="\n")
print(type(Animal),Animal.__doc__) #__doc__只对类有用,获得类的解释
7.文件输入输出
fp = open("name","r")
print(fp.read()) #原样读取数据
fp.close() #没使用一次文件都要关闭一次
fp = open("name","r")
print(fp.readline()) #读取第一行
fp.close()
fp = open("name","r")
print(fp.readlines()) #读取所有数据以列表形式返回
fp.close()
fp = open("writein","a+")
fp.write("this is the first line\n")
fp.close()
fp = open("writein","a+")
fp.writelines({"this is the second line\n","and this is the third line!\n"}) #write是输入一个字符串,writelines是输入一个列表
#w+指针在开始位置,第二个字符串将在前面
fp.close()
#异常处理
try:
fp = open("tzy.txt","r") #文件操作模式也要加“ ”
print(fp.readline())
except IOError: #异常的名字,类型是builtin(内置/内建)
print("没有该文件!")
#可以使用else
else:
print("成功打开了文件")
try:
ft = open("name","a+")
ft.write("ustc_tzy")
finally: #无论是否出错都会运行finally中的代码
print("无法写入文件")
#使用finally后面不再可以使用else
else:
print("成功打开文件")
fp = open("temp9.24.txt","w",encoding='UTF-8')
num=0
for i in range(1,10):
for j in range(1,i+1):
print(str(i) +" * "+str(j) + " = " + str(i*j),end="\t",file=fp) #使用print写文件记得加上file=“target”
print("\n",file=fp)
8.字符串函数及输出格式
import random
newtuple = (random.randint(10,100) for i in range(10))
print(tuple(newtuple))
print(tuple(newtuple))
str1 = " 20 20.9.22 ,tzy ,on macos"
newlist = str1.split()
print(newlist)
str2 = " @@@@@@www.badiu.com,hello!"
print(str2.count("@"))
print(str1+str2)
print(str2.find("@")) # 找到“@”第一次出现的位置,要是没有返回-1
print(str2.find("@",10)) # 从第10个字符开始找
print("@" in str2)
print(str2.index("@")) # 同find 但若没有会抛出异常
print(str2.rindex("@")) # 找到“@”最后一次出现的位置
str3 = "ustc_tzy 577"
print(str3)
print(str3[:1],str3[1:],str3[::2])
try:
str3[20]
except IndexError:
print("NOT EXISTS!")
str4=" hello word! "
print(str4)
print(str4.strip()) # Python strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。
print(str4) # strip()函数不会改变原来的字符串
print(str4.rstrip()) # Python rstrip() 删除 string 字符串末尾的指定字符(默认为空格).
print(str4)
str5 = "today,the cost is:%010.2f,the exponent of 10000 is :%.2E"
num = (21.1,10000)
print(str5%num)
str6 = ("today, my cost is: ${:,.2f},and the hexadecimal of 10000 is: "
"{:>#x},you have got surpass {:5.2%} of other people,the number of 50.23 is: {:>10.3f}")
print(str6.format(24.1,10000,0.9,50.23))
string = "21313 11321\n 1111"
print(string)
print(string.split(" "))
import re
url = "https://fanyi.baidu.com/translate?aldtype=16047&query=%E5from=baidu&smartresult=dict&lang=auto2"
pattern = r'[?|&]'
print(re.split(pattern,url))
str7 = " @tzy1 @tzy2 @tzy3 @tzy4@tzy5"
pattern = r'\s+@'
result = re.split(pattern,str7)
print (result)
for i in result:
if i !="":
print(i)
9.正则表达式
种类:
1)元字符
2)限定符
3)字符类
用**[ ]**括起来
4)排除字符
**[^a-zA-Z]**排除字母类型的数据
5)选择字符
**[1|3|6]**选择1,3,6中的任意一个
6)分组
**.**开头,0-9的数字选1-3个,重复3次
正则表达式由单引号括起来,在里面写上述规则
#以正则表达式字符匹配
#string matches
import re
# re.match(pattern,string,[flags])
pattern = r'mr_\w'
string = 'MR_SHOP mr_shop'
match = re.match(pattern,string,re.I) #re.I ignore case-sentitive and only one could be found
print(match)
print(match.group(),match.start(),match.end())
pattern = r'(13[4-9]\d{8}) | (15[0|1|2|8|9]\d{8})'
mobile = "13634222222"
match1 = re.search(pattern,mobile)
#print(match1.group())
if match1 == None:
print(mobile,"wrong")
else:
print(mobile,"correct")
#match从头开始匹配,search查找整个字符串所可以匹配的
#re.search(pattern,string,[flags]) flag==re.A 可以让\w不匹配汉字
#只匹配一个目标字符串
# re.findall(pattern,string,[flags])
#findall 查找整个字符串,获得所有匹配的目标,以列表形式返回
#以正则表达式替换字符串
#sub
#re.sub(pattern,repl,string,count,flags)
#repl 替换的字符串 count 进行替换的次数
pattern =r'177\d{8}'
string = "num1:13646556465 num2:17790200186"
replace = "i love you"
result = re.sub(pattern,replace,string)
print(result)
#split
#re.split(pattern,string,[maxsplit],[flag]) maxsplit最大拆分次数
string = " 21313 11321 1111"
result = string.split(" ")
print(result)
line = "Cats are smarter than dogs"
matchObj = re.match(r'(.*) are (.*?) .*', line, re.M | re.I)
print(matchObj)
if matchObj:
print("matchObj.group() : ", matchObj.group())
print("matchObj.group(1) : ", matchObj.group(1)) #匹配查到的第一个元组
print("matchObj.group(2) : ", matchObj.group(2))
else:
print ("No match!!")
10.字典与集合
#创建字典
#键唯一,值多个
#dictionay = {"key1":"value1","key2":"value2","key3":"value3",......,"key1":"valuex"}
#dict(zip(list1,list2))
list1 = ("t","z","y")
list2 = ["l","s","s"] #注意列表是[],元组是(),字典是{}
# temp = zip(list1,list2) #对象是两个元组
# print(temp,hex(id(temp))) #返回的是一个地址
# result1 = dict(temp)
result2 = {list1:list2} #也可以创建字典,但左边参数要是元组
# print(result1)
print(result2)
#空字典的创建
word = {}
word1 = dict()
print(word,word1)
#dict创建字典,但是左边元素不要用”“括起来
result3 = dict(t = "l",z = "s",y = "s")
print(result3)
#只知道key,不知道value
result4 = dict.fromkeys(list1)
print(result4)
#删除字典
# del result4
# print(result4)
#可以只删除字典元素而不删除字典
result4.clear()
print(result4)
#访问字典
print(result3["g"] if "g" in result3 else print("Not Exist!")) #注意索引的键值,无论元组列表还是字典,都是写在[]中
print(result3.get("t","Not Exist!")) #若不存在输出"Not Exist!"
dictionay = {"ustc":"tzy","sjtu":"z","zju":"y"} #可以创建多重字典
relationship = {"tzy":"lss"}
print(dictionay.get("ustc"))
print(relationship.get(dictionay.get("ustc")))
#遍历字典
print(dictionay.items())
for key,value in dictionay.items(): #字典内的键值对是以元组形式存储的,key和value是已经定义好了的
print(key,value)
print(type(dictionay),type(dictionay["ustc"]))
for key in dictionay.keys(): #输出所有键
print(dictionay.keys())
for value in dictionay.values(): #输出所有值
print(dictionay.values())
#添加删除修改字典元素
#添加
dictionay["pku"] = "y"
print(dictionay)
#修改
dictionay["pku"] = "yy" #若添加的键已经存在,会对值进行修改
print(dictionay)
#删除
del dictionay["pku"]
print(dictionay)
#字典推导式
import random
derivation = {i:random.randint(10,100) for i in range(1,5)} #和列表推导式不同,需要加上一个:
print(derivation)
name = ["tzy","tzyy","tzyyy"]
num = ["1","2","3"]
print(dict(zip(num,name)))
dictionay_ = {num:name for num,name in zip(num,name) }
print(dictionay_)
#集合:用来保存不重复的元素,最好的应用就是去重
#集合的创建 也是{},字典要以:分割成组存在,集合仅要单元素即可
set_ = {"tzy","tzyy","tzyyy","tzy"}
print(set_) #集合会自动去重,但每次输出无序,因此无法有索引获得元素
#空字典是{},空集合应该用set()
set1_ = set()
print(set1_,type(set1_))
list1 = ["1","2","3","1"]
print(set(list1)) #列表可以转换为集合
#集合添加和删除
#setname.add(element)
set1_.add("tzy")
set1_.add("tzyy")
print(set1_)
if "tzyyy" in set1_:
set1_.remove("tzyyy")
else:
print("Not Exist!")
print(set1_)
temp = set1_.pop() #删除第一个集合元素,并可以返回
print(temp + "\n" + str(set1_)) #集合类型要转换为字符串
set1_.clear()
print(set1_)
#集合交并差对称差集运算
#对称差集符号为^,表示去除两个集合都选了的元素
python = {"s1","s2","s3"}
c = {"c1","c2","c3","s1"}
print(str(python)+'\t\t'+str(c))
print(str(python & c)) #两个课都选了
print(str(python - c)) #选了python没选c
print(str(python | c)) #所有课程
print(str(python ^ c)) #排除两个课都选了
注:
1.规范是指dict遍历是不保证顺序的,但一定保证每个元素都被遍历一次
实现可以是无序,也可以是有序,都符合规范
但是无序不是说每次输出结果都不同,无序只是指结果不保证一定与插入顺序一致而已
2.字典对象的内置函数有:dictrname . {clear(),get(),items()}
3.打开文件,删除列表,字典,元组,字典都可以用if判断是否存在对应要删除的元素
4.集合内置函数:setname . {add(),remove(),pop(),clear()}
11.函数
#函数的创建和定义
def functionname(parameter):
"comments"
functionbody
import re
import datetime
def firstfunction(str_):
"you can filter the incorrect words by this function"
pattern = r"(lsss) | (tzyy)" #正则表达式单双引号都可以,若写成pattern = r"(lsss) | (tzyy)",则会/
# 将每一个l,s,t,z,y,“ ”都替换成***
print(str_)
result = re.sub(pattern,"***",str_)
print(result)
def empty():
pass #pass表示不做任何操作,相当于一个占位符,并且因为如果定义一个空函数程序会报错,当你没有想好函数/
# 的内容是可以用 pass 填充,使程序可以正常运行
firstfunction("i am tzyyy and lsss is my girlfirend")
#control+] 可以向右缩进
print(datetime.datetime.now().time())
#参数传递
#值传递:传递的参数是不可变数据类型;引用传递:传递的参数是可变数据类型
list1 = ["1","2","3"]
print(list1,id(list1))
list1[1] = "4"
list1.append(88)
print(list1,id(list1)) #改变其中元素,列表地址不变
list1 = ["4","5","6"]
print(list1,id(list1)) #若重新赋值,列表地址改变
dict1 = {1:"tzy",2:"lss"}
print(dict1,id(dict1))
dict1[3] = "tzyy"
print(dict1,id(dict1))
del dict1[1] #删除单个元素,但是无法修改元素
print(dict1,id(dict1))
dict1 = {1:"tz",2:"ls"} #若重新赋值,字典地址改变
print(dict1,id(dict1))
set1 = {2,1,3}
print(set1,id(set1))
set1.add(4)
print(set1,id(set1))
set1.remove(2) #是按元素删除的,也因为集合会随机输出,无法按下标索引
print(set1,id(set1))
set1 = {3,3,3}
print(set1,id(set1))
def BMItest(weight,height = 1.7): #为参数设置默认值,在无参数传递的时候使用默认值,在有参数的时候使用给定参数,默认参数要写到所有参数的后面
BMI=weight/(height*height)
print("你的BMI为:",BMI)
if BMI<18.5:
print("你的体重过轻")
if BMI>=18.5 and BMI<24.9:
print("你的体重正常")
if BMI>=24.9 and BMI<29.9:
print("你的体重过重")
if BMI >= 29.9:
print("肥胖")
BMItest(75)
#如果你有一些具有许多参数的函数,而你又希望只对其中的一些进行指定,那么你可以通过命名它们来给这些参数赋值——这就是python关键字参数
BMItest(height=1.8,weight=75)
print(BMItest.__defaults__) #可以查找某函数的默认值,仅用函数名就可以了,不用在后面加上括号
def demo(temp = []): #因为列表是可变数据类型,若调用两次会发现temp的值会使得列表有/
# 元素1,若想要不传参数就不会改变,则需要传递一个不可变数据类型
print(temp)
temp.append(1)
demo()
demo()
def demo1(temp = 1):
if(temp == 1):
print("请输出参数")
else:
print("i got it")
demo1()
demo1()
demo1(10)
#可变参数 即参数个数可变 咋没用呢
# *parameter/**parameter
def BMItest1(*p): #单星号会将传入的参数转换成列表 #shift+TAB向左缩进
for i in p:
for j in i:
weight = j[0]
height = j[1]
BMI = weight/(height*height)
print("你的身高是:",height,"你的体重是:",weight)
print("你的BMI为:",BMI)
if BMI<18.5:
print("你的体重过轻")
if BMI>=18.5 and BMI<24.9:
print("你的体重正常")
if BMI>=24.9 and BMI<29.9:
print("你的体重过重")
if BMI >= 29.9:
print("肥胖")
list2 = [[60,1.7],[50,1.64],[76,1.79]]
list3 = [[61,1.8]] #因为函数有双重循环,因此这里也有要双重列表
list4 = [[1.,2.],[4.,5.]]
BMItest1(list2,list3,list4)
def sign(**sign): #双星号会将传入的参数转换成字典
for key,value in sign.items():
print(key,"的星座是",value)
#sign(1="t",2="y",3="y") #字符串无法赋值给数字
list1_ = ["1","2","3"]
list2_ = ["t","z","y"]
result = dict(zip(list1_,list2_))
dict1 = {"q":"t","w":"y","e":"y"}
sign(**result,**dict1) #传字典需要在参数前面加上2个星号,且字典中此时的内容跟都要是字符串
#python中的参数本来就可以传入元组,列表,字符串,字典,集合,可变参数只是可以传入多个参数,/
# 在之中,单引号可变参数,适合传递多个列表,双引号可变参数适合传递多个字典
#返回值
goodsprice = []
def sale(goods):
origin = sum(goods)
new = origin
if 500 < origin < 1000:
new = origin * 0.9
if 1000 < origin < 1500:
new = origin * 0.8
if 1500 < origin < 2000:
new = origin * 0.7
return origin,new #多个参数以元组返回
while True:
temp = float(input("plz enter the price!And press 0 to end"))
if( temp == 0): #要将输入数据转换为整型或者浮点型,否则无法判断temp == 0
print("Checkout complete!")
break
else:
goodsprice.append(temp)
result = sale(goodsprice)
print("the origin is:",result[0],"now the price is:",result[1])
#变量的作用域
i = 1
def f():
global i
i = 2 #若要在函数内修改全局变量,需要先定义后赋值,不能一次完成
#不能在函数内直接修改全局变量
print("在函数内,i修改后的值为", i)
f()
print("在函数外,i的值为",i)
j = 1
def f1():
j = 2
print(j)
print(j)
f1()
print(j)
#匿名函数 对不重要,用得少或仅用一次的函数不需要去名字
import math
def cal(r):
return r*r*math.pi
print(cal(10))
result = lambda r:r*r*math.pi #lamda 参数1,参数2...:函数体,返回的是lamda类型
print(type(cal),type(result),float(result(10)))
#sort可以指定两个排序方式,用key=rule1,rule2 都是升序排列
list1 = [1,2,3,4]
list2 = list1[:] #可以通过分片操作复制列表
list3 =list2
print(list1,list2,list3)
#Python预置的list.sort()、sorted()方法可实现各种数组的排序,但支持的只限于一个key,如/
# 果要多重排序,目前所知的方法只有自定义了。
import random
list4 = [random.randint(10,100) for i in range(10)]
print(list4)
list4.sort(reverse=True) #会更改实际的排序情况
print(list4)
shopping = [["牙膏",10],["洗面奶",20],["洗面奶",15]]
print(shopping)
shopping.sort(key = lambda x:(x[0],-x[1])) #先按货品名称字典序升序排序,再按价格降序排序
print(shopping)
result = lambda x:(x+1,x+2) #lambda的表达式是返回值,用逗号隔开,若有多个表达式,需要用括号括起来
print(result(1))
# def is_odd(n):
# return n % 2 == 1
tmplist = filter(lambda n:n % 2 == 1, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
newlist = list(tmplist)
print(newlist)
12.杂项
# map() 会根据提供的函数对指定序列做映射。
# 第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。
list1 = [1,2,3,4]
def square(i):
return i*i
result1 = map(square,list1)
result2 = [i*i for i in list1]
result3 = map(lambda x:x*x,list1) #使用函数都会返回map类型的数据,无论是定义好的函数还是匿名函数
print(type(result1),type(result3))
print(list(result1),result2,list(result3))
#reduce(function, iterable[, initializer])函数会对参数序列中元素进行累积。
#函数将一个数据集合(链表,元组等)中的所有数据进行下列操作:用传给 reduce 中的函数function(有两个参数)/
# 先对集合中的第 1、2 个元素进行操作,/
# 得到的结果再与第三个数据用 function 函数运算,最后得到一个结果。
from functools import reduce
#python3中的reduce函数和python2.7不在同一个库里了,使用的时候要注意。/
# Python3使用reduce函数要先:from functools import reduce
list2 = [1,2,3,4,5]
result4 = reduce(lambda x,y:x+y,list2)
#lambda是对传入进来的参数,按照表达式返回结果的一种函数,但是传入/
# 的数据是列表,会自动取需要的参数数量进行计算直至列表为空
print(result4)
list3 = [[1,"tzy"],[1,"azy"],[2,"lss"]]
list3.sort(key=lambda x:(x[0],x[1]))
print(list3)
#类
#类的定义和创建类的实例 命名使用“驼峰式命名法”多个单词开头字母均为大写
class Goose:
#下面是类属性
say = "human are my slaves!"
num = 0
ordinals = {1:"first",2:"second",3:"third"}
#java可以由输出参数不同使用不同的构造方法,python仅可以定义一种构造方法,多个构造方法将会使用最后一个用于构造
def __init__(self,_beak,_wings,_claw): #定义构造方法,self必须是第一个参数,不过self是一个约定,可以用别的名字
"大雁类"
#pass #若没想好类需要做什么
self.beak = _beak #实例属性,self表示自己,在类中(包括其他函数)都可以访问
self.wings = _wings
self.claw = _claw
sa = 1
Goose.num += 1
print(self.beak,self.wings,self.claw)
print("rua!" + Goose.say + "I am your the %s lord goose"%Goose.ordinals[Goose.num],sa #使用类定义的属性,需要类名.属性来访问
def character(self):
self.claw = "99" #在别的函数中定义的实例属性,可以在另一个函数中使用(普通属性也可以)
sa = 99
print("我是鹅,我的"+self.beak+"我"+self.wings+",我的"+self.claw,sa)
def eat(self,shout = "i need food!"):
print(shout)
# wildGoose = Goose("喙很长","有双翅","爪子是蹼") #创建大雁类实例
# print(wildGoose) #其是返回Goose对象
# wildGoose.eat("peanut is delicous!")
# wildGoose.character()
#
# wildGoose1 = Goose("1","2","3")
# wildGoose1.eat()
# wildGoose1.character()
# list1 = []
# for i in range(3):
# print(list1.append(Goose(str(i),str(i+1),str(i+2))))
# print(list1) #list1存放了三个Goose对象
#
# Goose.high = 1.8 #添加新的类属性
# print(list1[1].high)
# class Temp:
# def __init__(self):
# print("hello!")
#
# print(Temp()) #直接调用类名(),会自动执行构造方法__init()__,还会自动返回类的类型’
newGoose = Goose("1","2","3")
print(newGoose.character()) #类的实例属性在类外用实例访问
#类的访问权限
#python无权限修饰符
# _foo:proteced 只允许类本身和子类及其实例进行访问
# __foo:private 只能类本身访问,类的实例不可以访问,但可以类的实例名._类型__XXX(函数或者属性)
# __foo__系统定义的函数或属性
class Swan:
'天鹅类'
__character = "Hello!"
#python会将所有__Name类的变量改名字为_ClassName__Name,但在类中的方法调用,不会受外面修改的影响
def __init__(self):
print("this is a new swan!")
def f(self):
print(Swan.__character)
swan = Swan()
print(swan._Swan__character) #不可以用实例访问保护类变量(swan.__character),但可以由左边形式访问(可以修改)
swan._Swan__character = "tzy!!!!"
print(swan._Swan__character) #对保护变量的修改,会在外部实现,但是不会在类中发生变化
swan.f()
#property属性,用于计算的属性:将函数转换为方法(也称为装饰器)
class Caltimes:
def __init__(self,_long,_width):
self.long = _long
self.width = _width
def cal(self):
return self.long*self.width
@property
def cal1(self):
return self.long*self.width
rectangle = Caltimes(15,17)
print(rectangle.cal(),rectangle.cal1) #使用装饰器可以将函数变成属性,调用时不用加括号,但是无法对这种属性赋值
#__Name形式虽然保护了变量,但是也无法再用实例来修改或者读取了,为了能用实例来读取,使用了装饰器
class TVProgram:
TVlist = ["the big short","top gear","TED speaking","ready one player"]
def __init__(self,program_):
self.__program = program_
def get(self):
print(self.__program)
#@property.setter #使其可以修改,好像现在的版本不可以了:”descriptor 'setter' for 'property' objects doesn't apply to a 'function' object“
def change(self,temp):
if temp in TVProgram.TVlist:
self.__program = temp
print("now,you chose the"+temp)
else:
self.__program = "the film doesn't exist"
@property
def get1(self):
print(self.__program)
p = TVProgram("top gear")
p.get1
film = input("plz enter the movie you want:\t")
p.change(film)
p.get1
# p1 = TVProgram("idea worth spreading")
# p1.get1 #只读,无法修改,其实和上述直接调用类函数一样
#继承
#继承定义:class ClassName(BaseClass1,BaseClass2...):
class Fruit:
def color(self,co):
self.co = co
@property
def get(self):
print("the color of fruits is\t"+self.co)
class Apple(Fruit):
def __init__(self,co):
self.co = co
def get(self):
print("the color of apple is\t"+self.co)
class Pear(Fruit):
def __init__(self,co):
self.co = co
def get(self): #重写方法,若是Pear的实例来调用便使用这个函数
print("the color of pear is\t"+self.co)
apple = Apple("red")
apple.get()
pear = Pear("Yellow")
pear.get()
pear.color("green")
pear.get()
fruit = Fruit()
fruit.color("white")
fruit.get #使用@property仅在本身类的函数中有用,子类无法使用4
#在派生类调用父类的__init()__方法
class Fruit:
sum_ = 0
co = "绿色"
def __init__(self,co_):
print(Fruit.sum_) #即使在同一个类中和,方法无法直接访问类的属性,只能通过类名“.”来访问
Fruit.co = co_
@property
def get(self):
print("the color of fruits is\t"+self.co)
class Apple(Fruit):
def __init__(self,co):
self.co = co
# super().__init__() #调用父类的__init()__方法,super内无论写不写参数需要在方法/函数中实现
# super(Apple,self).__init__() #用于调用被覆盖的父类方法
def get(self):
print("the color of apple is\t"+self.co)
print(Fruit.sum_)
class Pear(Fruit):
def __init__(self,co):
super(Pear, self).__init__(co) #为基类方法传递参数,子类修改基类
def get(self): #重写方法,若是Pear的实例来调用便使用这个函数
co = "white"
print("the color of pear is\t"+Fruit.co+"and the color in this class is:"+co)
#something = Fruit()
apple = Apple("purple")
apple.get()
pear = Pear("黄色")
pear.get()
13.包和模块
#模块:可以防止函数或者变量名冲突,不同模块的命名空间不同
#不能使用和python自带模块相同的名字,导入模块或者模块中的类和方法的时候不用加上“.py”
#命名规则:(1)模块推荐使用小写命名,(2)除非有很多字母,尽量不要用下划线,因为很多模块文件存与模块名称一致的类,/
# 模块采用小写,类采用首字母大写,这样就能区分开模块和类。
import bmi
from bmi import *
#在顶级模块中执行时,__name__的名字就是__main__,导入到其他模块中,__name__的名字是模块的名字
if __name__ == '__main__': #让某些代码只能在本模块中运行,若是导入到其他模块,就不会运行,注意是双等于号
bmi.BMI() #因为可能有多个命名空间有BMI()函数,所以需要指定命名空间bmi
#BMI() #直接从模块中导入函数或者类,就不需要加上命名空间了
#print(dir()) #可以在最后找到导入的内容
#模块搜索目录
#让导入某块不在一个文件中,可以通过在环境变量中增加
import sys
print(sys.path) #导入模块时查找的路径
#临时添加查找目录
#sys.path.append("D:/CODE/demo_py/function") #若使用”\“则需要添加两个”\“,否则如左换成"/"
#print(sys.path)
import bmi
bmi.BMI()
#python中的包:有__init__.py的文件夹,__init__.py可以为空
#相当于将模块打包一起用
#import demo.shape #每次使用都要包名.模块名.对象,很麻烦
from demo import shape #这种方法就只需要用模块名.对象。
print(shape._length,shape._width) #但若不同包中有同名模块,则还是需要包.模块
from demo.shape import * #可以直接导入包中的模块中的对象,import后面可以是*
#保护变量,在外部(非同一个py文件)访问,需要"模块名."访问
print(shape._width,shape._length) #但若不同模块中有同名对象,则还是需要模块.对象
getvalue()
changevalue(1920,1080)
getvalue()
'''
import verificationcode
print(verificationcode.verrification())
import animal
tiger = animal.Animal("yellow","tiger") #引入别的包然后创建对象实例
tiger.getinfo()
12.杂项
str = "tzy121434244644546466464646/" \ #可以用/截断过长的语句
"461311"
print(id(str))
str = "lss"
print(id(str)) #证明string是不可变数据类型
x=1;y=2
print(x,y)
x,y=y,x
print(x,y) #交换数据的一种简单方法
'''
'''
#多行语句可以用;在一行内运行
print("tzy!",end="");print("lss!")
#foo means Function Object Oriented
foo = "ustc_tzy"
for i in foo:
print(i,end=" ")
for i in range(len(foo)):
print('f[%d]'%i,foo[i])
list = [x*x for x in range(11) if x%2 == 0] #列表推导式可以再数据范围用if进一步限制范围
print(list)
命名规范
注: 使用双下划线"__"开头的实例变量或方法是类私有的
保留字:
标识符:
不能使用@¥%…
运算符优先级:
Python没有专门的常量定义,尽量少用常量,python可以动态修改数据
a = 1
b = 1
print(id(a), id(b), a is b, a == b) #is是判断地址是否相等的操作符,因为a,b都指向对象1,所以两者地址相同
a = 2 #a指向的地址是id(2)
print(id(a),id(2))
a = "123"
b = "123"
print(a is b)
a = 1.1
b = 1.1
print(a is b)
a = (1,)
b = (1,)
print(a is b)
#可变数据类型,dict,set,list 存储的数据的位置和不可变数据类型的位置不一样,多次定义会申请多个地址空间,这些数据类型也是嵌套引用的类型
a = {"t":1}
b = {"t":1}
print(a is b, id(a),id(b))
a = {1,2,3}
b = {1,2,3}
print(a is b, id(a))
a = ['a', '1']
b = ['a', '1']
print(a is b, a == b, id(a))
# 140712593983136 140712593983136 True True
# 140712593983168 140712593983168
# True
# True
# True
# False 1937653124224
# False 1937665786592
# False True 1937664431616
数据类型转换
int(),float(),str(),hex() 16进制,oct() 8进制,bin() 2进制