Python学习笔记

2018-01-18  本文已影响0人  JUNjianshuZHU
1
2
print(r'hello,\n')
->hello,\n

print('hello,\n')
->hello,

3
5/3
Out: 1.6666666666666667

5.0/3
Out: 1.6666666666666667

5.0//3
Out: 1.0

5.0%3
Out: 2.0

4.break的用法
5.continue的用法
6.函数的局部变量
7.为定义在函数外的变量赋值的
8.为函数设置默认参数值
8.注意格式
9.使用关键参数
10.return的用法
10.未指定返回值能返回空置
#如果有多个返回值,将会以元组形式返回
def hello():
    return 'asdasdasd',1235,True,'dSA;LFKASPDFIKL'

hello() --->('asdasdasd', 1235, True, 'dSA;LFKASPDFIKL')

11.文档字符串DocStrings
11.用法
12.
# file_name:mymodule.py (主程序)

def sayhi():
    print('hi,you are success!!!')
    
version = '0.1'

if __name__ == '__main__':
    print('load in the program')
else:
    print('load out of the program')    

# end of mymodule.py
# file saved in C:\Users\ye\Anaconda3
# filename:myothermodule.py(调用主程序)

import mymodule

mymodule.sayhi()

print('Version is ',mymodule.version)

# end of myothermodule.py
# file saved in C:\Users\ye\Anaconda3
12.结果
13.元组
13.单元素元组
14.字典循环
15.列表切片
shoplist = ['apple', 'mango', 'carrot', 'banana']
# Slicing on a list
print('Item 1 to 3 is', shoplist[1:3])  --->  Item 1 to 3 is ['mango', 'carrot']
print('Item 2 to end is', shoplist[2:])  --->  Item 2 to end is ['carrot', 'banana']
print('Item 1 to -1 is', shoplist[1:-1])  --->  Item 1 to -1 is ['mango', 'carrot']
print('Item start to end is', shoplist[:])  --->  Item start to end is ['apple', 'mango', 'carrot', 'banana']

16.字符串切片
# Slicing on a string
name = 'swaroop'
print('characters 1 to 3 is', name[1:3])  --->  characters 1 to 3 is wa
print('characters 2 to end is', name[2:])  --->  characters 2 to end is aroop
print('characters 1 to -1 is', name[1:-1])  --->  characters 1 to -1 is waroo
print('characters start to end is', name[:])  --->  characters start to end is swaroop

17.对象和参考
shoplist = ['apple', 'mango', 'carrot', 'banana']      #创建了列表shoplist
mylist = shoplist      # 仅传递了指针
del shoplist[0]
print('shoplist is', shoplist)  --->  shoplist is ['mango', 'carrot', 'banana']      #apple同时在shoplist和mylist消失
print('mylist is', mylist)  --->  mylist is ['mango', 'carrot', 'banana']
mylist = shoplist[:]      #!传递了值
del shoplist[0]
print('shoplist is', shoplist)  --->  shoplist is ['carrot', 'banana']
print('mylist is', mylist)  --->  mylist is ['mango', 'carrot', 'banana']

18.字符串方法
20.继承1
class SchoolMember:   #父类
    '''Represents any school member.'''
    def __init__(self, name, age):
        self.name = name
        self.age = age
        print ('(Initialized SchoolMember: %s)' %self.name)
    def tell(self):
        '''Tell my details.'''
        print ('Name:"%s" Age:"%s"' % (self.name,self.age))

class Teacher(SchoolMember):
    '''Represents a teacher.'''
    def __init__(self, name, age, salary):
        #子类继承,注意使用super().
        super().__init__(name, age)   
        self.salary = salary
        print ('(Initialized Teacher: %s)' % self.name)
    def tell(self):
        super().tell()
        print ('Salary: "%d"' % self.salary)

class Student(SchoolMember):
    '''Represents a student.'''
    def __init__(self, name, age, marks):
        super().__init__(name, age)
        self.marks = marks
        print ('(Initialized Student: %s)' % self.name)
    def tell(self):
        super().tell()
        print ('Marks: "%d"' % self.marks)

t = Teacher('Mrs. Shrividya', 40, 30000)
s = Student('Swaroop', 22, 75)

members = [t, s]

for member in members:
    member.tell()                    # works for both Teachers and Students

--->
(Initialized SchoolMember: Mrs. Shrividya)
(Initialized Teacher: Mrs. Shrividya)
(Initialized SchoolMember: Swaroop)
(Initialized Student: Swaroop)

Name:"Mrs. Shrividya" Age:"40"
Salary: "30000"
Name:"Swaroop" Age:"22"
Marks: "75"
21.多态

class Person:
    '''Represents a person.'''
    population = 0      #计数器,累计调用的次数,但不受新的调用对象而初始化
    def __init__(self, name):
        '''Initializes the person's data.'''
        self.name = name
        print ('(Initializing %s)' %self.name)
        # When this person is created, he/she adds to the population
        Person.population += 1      #计数器,累计调用的次数,但不受新的调用对象而初始化
        
    def sayHi(self):
        print ('Hi, my name is %s.' %self.name)
        
    def howMany(self):
        '''Prints the current population.'''
        if Person.population == 1:
            print ('I am the only person here.')
        else:
            print ('We have %d persons here.' %Person.population)

swaroop = Person('Swaroop')
swaroop.sayHi()
swaroop.howMany()

print('-'*50)

kalam = Person('Abdul Kalam')
kalam.sayHi()
kalam.howMany()

print('-'*50)

swaroop.sayHi()
swaroop.howMany()

--->
(Initializing Swaroop)
Hi, my name is Swaroop.
I am the only person here.      #计数器的结果
--------------------------------------------------
(Initializing Abdul Kalam)
Hi, my name is Abdul Kalam.
We have 2 persons here.      #计数器的结果
--------------------------------------------------
Hi, my name is Swaroop.
We have 2 persons here.      #计数器的结果

21.type 和 isinstance

type('520')      #判断输入的类型
Out[1]: str

type(5.2)
Out[2]: float

type(True)
Out[3]: bool

type(5e10)
Out[4]: float

isinstance('520',str)      #判断是否一致 
Out[5]: True

isinstance('520',int)
Out[6]: False

isinstance(2.2,int)
Out[7]: False

isinstance(2,int)
Out[8]: True

isinstance(5.2,float)
Out[9]: True

22. 在列表中加入元素的3种方法

list = ['a','b','c']      # 创建一个列表list
print(f'before:{list}')  --->  before:['a', 'b', 'c']

list.append('d')      #在list后面加上‘d’
print(f'after append:{list}')  --->  after append:['a', 'b', 'c', 'd']

add = ['e','f']
list.extend(add)       #在list后面加上‘e’‘f’
print(f'after extend:{list}')  --->  after extend:['a', 'b', 'c', 'd', 'e', 'f']

list.insert(0,'0')      #在list的指导位置加上‘0’
print(f'after insert:{list}')  --->  after insert:['0', 'a', 'b', 'c', 'd', 'e', 'f']

23. 在列表中删除元素的3种方法

list = ['a','b','c','e','f']      # 创建一个列表list
print(f'before:{list}')  --->  before:['a', 'b', 'c', 'e', 'f']

pop1 = list.pop()      #pop()默认删除末尾元素并返回删除的元素
print(pop1)  --->  f
print(f'after pop1:{list}')  --->  after pop1:['a', 'b', 'c', 'e']

pop2 = list.pop(0)      #pop(0)可以删除指定位置的元素
print(pop2)  --->  a
print(f'after pop2:{list}')  --->  after pop2:['b', 'c', 'e']

remove = list.remove('b')       #remove需要输入删除元素的值
print(remove)  --->  None
print(f'after remove:{list}')  --->  after remove:['c', 'e']

del list[0]      #del需要输入删除元素的位置
print(f'after del:{list}')  --->  after del:['e']

del list      #del还可以直接删除整个列表
print(f'after del:{list}')  --->  after del:<class 'list'>

24.列表的数数、查找位置、排序

list = ['a','b','b','c','e','f']       # 创建一个列表list

list.count('b')       # 在list数数‘b'的个数
Out[30]: 2

list.index('b')      # 在list查找‘b'的位置
Out[31]: 1

list.index('b',2,)      # 在list查找‘b'的位置,可以指定查找的开始和结束位置
Out[32]: 2

list2 = [1,5,3,8,4,6,0]

list2.reverse()      # 逆序排列list2
Out[37]: [0, 6, 4, 8, 3, 5, 1]

list2.sort()       # 对list2进行排序
Out[39]: [0, 1, 3, 4, 5, 6, 8]

list2.sort(reverse=True)      # 对list2进行逆序的排序
Out[41]: [8, 6, 5, 4, 3, 1, 0]

25.元组

tuple1 =(1)      # 元组的要素是逗号
Out[47]: int

tuple1 =2,3,4
Out[49]: tuple

tuple1 =()
Out[51]: tuple

tuple1 =(1,)
Out[53]: tuple

tuple1 =1,
Out[56]: tuple

tuple2 = ('a','b','d','e')
tuple2 = tuple2[:2] + ('c',) + tuple2[2:]      # 在元组中增加元素的方法
Out[59]: ('a', 'b', 'c', 'd', 'e')

27. for的其他写法

list1 = list(range(10))
list2 = [i*2 for i in list1 if i > 5]
print(list2)

--->
[12, 14, 16, 18]

28. 在函数中接收元组和列表

def powersum(power, *args):      
#在 args 变量前有 * 前缀,所有多余的函数参数都会作为一个元组存储在 args 中。如果使用的是 ** 前缀,多余的参数则会被认为是一个字典的键/值对
    total = 0
    print(f'args:{args}')
    for i in args:
        total += pow(i, power)
    print(total)
    
powersum(2,3,4)      #调用函数

--->
args:(3, 4)
25

29. 字符串函数partition和split的区别

str1 = 'learn python the hard way'

str1.partition()      # partition必须提供参数,否则报错
TypeError: partition() takes exactly one argument (0 given)

str1.partition('th')      # partition将字符串切割成元组
Out[3]: ('learn py', 'th', 'on the hard way')

str1.split()      # split默认按照空格将字符串切割成列表
Out[4]: ['learn', 'python', 'the', 'hard', 'way']

str1.split('th')      # split也可提供切割参数
Out[5]: ['learn py', 'on ', 'e hard way']

30. enumerate和zip

a = (1,2,3,4,5)
b = [6,7,8,9,10]

enumerate(b)
Out[22]: <enumerate at 0x1c9e74107e0>

tuple(enumerate(b))      # 将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列
Out[23]: ((0, 6), (1, 7), (2, 8), (3, 9), (4, 10))

zip(a,b)
Out[24]: <zip at 0x1c9e73f3048>

tuple(zip(a,b))      #将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表
Out[25]: ((1, 6), (2, 7), (3, 8), (4, 9), (5, 10))

31.format的注意事项

print('{0} is {1} {2} day!'.format('today','a','sunny'))
--->today is a sunny day!

print('{a} is {b} {c} day!'.format('today','a','sunny'))
--->报错

print('{a} is {b} {c} day!'.format(a='today',b='a',c='sunny'))
--->today is a sunny day!      #需要说明a,b,c各代表什么

'{0:.1f}{1}'.format(27.658,'gb')
Out[144]: '27.7gb'

32.收集参数

def test(*params):
    print('参数的长度是:',len(params))
    print('第二个参数是:',params[1])
    
test(1,'工作簿',3.14,50,88,60)      #所有参数全部传递给形参params

--->
参数的长度是: 6
第二个参数是: 工作簿
def test(*params,exp):
    print('参数的长度是:',len(params))
    print('第二个参数是:',params[1])
    
test(1,'工作簿',3.14,50,88,60)      #没有参数传递给exp,因此报错

--->
TypeError: test() missing 1 required keyword-only argument: 'exp'
def test(*params,exp):
    print('参数的长度是:',len(params))
    print('第二个参数是:',params[1])

test(1,'工作簿',3.14,50,88,exp=60)      #指定把参数60传递给exp

--->
参数的长度是: 5      #注意第一个参数长度变为5!
第二个参数是: 工作簿

33.函数嵌套

def fun1():      #第一层函数
    print('fun1 is working...')
    def fun2():      #第二层函数
        print('fun2 is working......')
    fun2()      #调用fun2
        
fun1()

--->
fun1 is working...
fun2 is working......

34.闭包和函数调用
def funx(x):
    def funy(y):
        return x*y
    return funy      #注意带参数函数的返回格式

i = funx(5)(8)
print(i)      ---> 40
def funout():
    def funin():
        print('bingo!')
    return funin()      #!注意返回值

funout() --->bingo!
def funout():
    def funin():
        print('bingo!')
    return funin      #!注意返回值,同上区别

funout()() --->bingo!       #!注意调用区别
def Fun1():
    x = 5
    def Fun2():
        nonlocal x
        x *= 5
        return x
    return Fun2

a = Fun1()

print(a()) --->25
print(a()) --->125      #再次调用时并没有初始化a
print(a()) --->625

35.非局部变量声明

def fun1():
    x = 5
    def fun2():
        nonlocal x      #在嵌套函数中引用,必须声明为非局部变量
        x *= x
        return x
    return fun2()

fun1()   --->  25  

36.lambda函数

def ds(x):
    return 3*x+10
ds(10)     --->  40

a = lambda x : 3*x+10
a(10)   --->  40

37.过滤器filter()

list(filter(None,[0,1,2,True,False]))
---> [1, 2, True]      #过滤掉0和False

应用:筛选奇数
def odd(x):
    return x % 2

temp = range(10)
show = filter(odd,temp)
list(show)      --->[1, 3, 5, 7, 9]

38.迭代器map()

def square(x):
    return x ** 2

temp = range(10)
show = map(square,temp)
list(show)    --->[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

39.创建字典的方法

dict1 = {'李宁':'一切皆有可能','耐克':'just do it','阿迪达斯':'impossible is nothing'}      #方法1
---> {'李宁': '一切皆有可能', '耐克': 'just do it', '阿迪达斯': 'impossible is nothing'}

dict2 = dict((('f',70),('i',105),('s',115),('h',104),('c',67)))      #方法2:利用元组来创建字典
---> {'c': 67, 'f': 70, 'h': 104, 'i': 105, 's': 115}

dict3 = dict(one='1',two='2',three='3')      #方法3:赋值创建
---> {'one': '1', 'three': '3', 'two': '2'}

dict.fromkeys((1,2,3),'good')      #方法4:fromkeys()
---> {1: 'good', 2: 'good', 3: 'good'}
补充
40.dict内建的函数

dict3 = dict(one='1',two='2',three='3')

dict3.keys()      #返回键
---> dict_keys(['one', 'two', 'three'])  

dict3.values()      #返回值
---> dict_values(['1', '2', '3'])

dict3.items()      #返回键值对
--->  dict_items([('one', '1'), ('two', '2'), ('three', '3')])
dict3.get('one','no')      #查找键对应的值,如果没有返回'no'      
--->   '1'

'one' in dict3      #也可以用in 或 not in
--->  True

'1' in dict3
--->  False

1 in dict3
--->  False
dict4 = dict3.copy()      #字典拷贝,改变dict3的值不影响dict4
--->  {'one': '1', 'three': '3', 'two': '2'}

dict3.clear()      #清空字典
--->  {}
dict3.setdefault('four','4')      #查找键,如果没有则设为默认值
--->  '4'

dict3
--->  {'four': '4', 'one': '1', 'three': '3', 'two': '2'}
dict1
--->  {'耐克': 'just do it'}

dict3.update(dict1)      #将dict1的键值插入到dict3
--->  {'four': '4', 'one': '1', 'three': '3', 'two': '2', '耐克': 'just do it'}
'''对字典的值进行排序'''
>>> xs = {'a': 4, 'b': 3, 'c': 2, 'd': 1}

>>> sorted(xs.items(), key=lambda x: x[1])      #xs.items()返回元组(键,值)
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]

41.集合
a = {1,2,3}
type(a)  --->  set      #a是一个集合

b = set([1,2,3])  --->  {1, 2, 3}      #set函数可以把列表、元组、字符串变成集合

c = (set[1,2,3,4,5,4,3,2,1])  --->  {1, 2, 3, 4, 5}      #转成集合的可以去重复数据
集合相关函数
e = {1, 2, 3, 4, 5}

e.add(6)  --->  {1, 2, 3, 4, 5, 6}      #增加数据

e.remove(6)  --->  {1, 2, 3, 4, 5}      #删除数据

f = frozenset(e)      #冻结集合     
f.add(6)      #冻结的集合不能做更改,否则会报错

操作文件,具体使用看例题3
42.文件写入知识点:
write()和writelines()的区别:
1、write() 需要传入一个字符串做为参数,否则会报错
2、writelines()  参数必须是list/string/dict/tuple 等可迭代序列对象,且里面内容须是字符,那么使用writelines()的时候,它会自动迭代里面的内容并写入文件,但是要注意的是,它只是单纯的按顺序把内容写入,不会在每个被迭代元素后面加任何东西。
l = [1, 3, 5]     writelines(l)     显示:TypeError: writelines() argument must be a sequence of strings
l1 = ['1', '3', '5']     writelines(l1)       往文件存入135
l2 = '246'       writelines(l2)      往文件存入246

write()  参数只能是string,同时只是单纯的加入内容,不会在内容后面添加任何东西。
s = '345'   write(s)      往文件存入345

44.pickle模块
作用:将代码需要用到的字典、列表等数据封装成二进制文件存储,减少代码体积

import pickle      #导入模块

first_list = [1,2,'a','b',['一','二']]  

f = open('my_list.pkl','wb')      #!以‘wb’方式创建一个.pkl的文件
pickle.dump(first_list,f)      #将列表“倒入”上述文件
f.close()

j = open('my_list.pkl','rb')      #!以‘rb’方式读取上述文件
second_list = pickle.load(j)      #将文件内容“装载”到列表
print(second_list)      #查看结果

---> [1,2,'a','b',['一','二']]  

45.异常处理

a = dict(a=1,b=2,c=3)      #设置一个字典

try:            #放入可能会造成异常的代码
    print(a['a'])
except KeyError as reason:  #!出现指定异常类型需要执行的代码,reason用于传递异常说明
    print(': %s' %reason)
except OSError:  #可以指定多个异常类型
    print('操作系统错误')
else:      #如果没有异常则执行else
    print('else')
finally:  #无论如何都会执行的代码
    print('end')

--->1
     else
     end

46.子类调用父类函数的方法1:
class Person():      #父类
    def __init__(self,x):
        self.x = x        
    def printx(self):
        print('father\'x is: ',self.x)        
        
class Child(Person):      #子类
    def __init__(self,y):
        super().__init__(y)      #!由于子类的__init__覆盖了父类的,因此需要声明,并且可以传参数进去
        self.y = y        
    def printy(self):
        print('child\'y is: ',self.y)
方法2:
class Person():
    def __init__(self,x):
        self.x = x        
    def printx(self):
        print('father\'x is: ',self.x)
         
class Child():
    def __init__(self,x,y):
        self.x = Person(x).printx()      #!与上面的区别
        self.y = y
    def printy(self):
        print(f'y is {self.y}')

a1 = Child(10,5)      --->  father'x is:  10
a1.printy()      --->  y is 5
47.(1)关于类的其他需要注意内容:
class Person():
    def __init__(self):      #!如果__init__里面没有参数的话,实例过程中不需要传递参数
        print('__init__')      
        #return self      #! __init__不能有返回对象,不然程序报错
    def printx(self,x):      #!self不可以省略
        print('father\'x is: ',x)
        
p1 = Person()  --->__init__      #实例初始化自动调用 __init__  函数
p1.printx(5)  --->father'x is:  5      #!这里传递了2个参数:self,5
(2)删除类:
class CC():
    def setXY(self,x,y):
        self.x = x
        self.y = y
        print(self.x,self.y)

c1 = CC()      #实例化c1
c1.setXY(11,99)  --->11 99

del CC      #删除类CC
c1.setXY(11,99)  --->11 99      #删除类后原实例没有删,即图纸烧了,房子还在
c2 = CC      #报错,删除后不能再实例化

更多关于类的内容看这里:一篇文章搞懂Python中的面向对象编程


48、必选参数、默认参数、可变参数、关键字参数
def f1(a,b,c=0,*args,**kw):  
    print(a,b,c,args,kw)  
  
#调用情况:  
f1(1,2)  --->1 2 0 () {}  
f1(1,2,c=4)  --->1 2 4 () {}
f1(1,3,6,'aw','wad',x=123,y='1232')  --->1 3 6 ('aw', 'wad') {'x': 123, 'y': '1232'}


a,b 为必选参数
c=0 为默认参数
*args 为可变参数,可变参数允许你传入 0个或任意个参数,这些可变参数在函数调用时自动组装为一个tuple
**kw 为关键字参数,关键字参数允许你传入 0个或任意个含参数名的参数,这些关键字参数在函数内部自动组装为一个dict  

上一篇下一篇

猜你喜欢

热点阅读