1、lambda函数及好处;
lambda函数可接收任意多个参数,并且返回单个表达式值的函数;
lambda不能包括指令,包括的表达式只能超过一个;
2、Fibonacci数列;
小于100数列:
a,b = 0 ,1
while b < 100:
print(b),
a,b = b,a+b
3、删除list里重复元素:
l = [1,1,2,3,4,5,4]
#方法一
print(list(set(l)))#方法二
d = {}
for x in l:
d[x] = 1
mylist = list(d.keys())
print(mylist)
4、类继承:
class A(object):
def show(self):
print("base show")
class B(A):
def show(self):
print("dervied show")obj=B()
obj.show()
输出:
dervied show
问题:输出A的show方法:
class A(object):
def show(self):
print("base show")
class B(A):
def show(self):
print("dervied show")obj=B()
obj.show()obj.__class__ = A
obj.show()
输出:
dervied show
base show
5、方法对象:
下述代码正常运行,添加内容:
class A(object):
def __init__(self,a,b):
self.__a = a
self.__b = b
def myprint(self):
print("a = ",self.__a,"b = ",self.__b)a1 = A(10,20)
a1.myprint()a1(80)
实现__call__方法:
class A(object):
def __init__(self,a,b):
self.__a = a
self.__b = b
def myprint(self):
print("a = ",self.__a,"b = ",self.__b)
def __call__(self,num):
print("call:",num + self.__a)a1 = A(10,20)
a1.myprint()a1(80)
输出:
a = 10 b = 20
call: 90
6、交换两个变量的值:
a = 10
b = 20
(a,b) = (b,a)
7、python3中没有xrange;
8、包管理:
问题:一个包里有三个模块,mod1.py/mod2.py/mod3.py,使用from package import *导入模块时,怎么保证只有mod1、mod3被导入;
方法:在__init__.py文件中,添加__all__ = ['mod1','mod3']
9、闭包;
函数接收一个整数,返回一个函数,功能是把函数的参数和n相乘,返回结果;
def mul(num):
def gn(val):
return num * val
return gna = mul(10)
print(a(20))
输出:
200
10、性能:
问题:下面代码慢在哪里?
def strest1(num):
str = "first"
for i in range(100):
str += 'X'
return strprint(strest1(10))
输出:
firstXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX原因:str为不可变对象,每次迭代,会生成新的str对象存储新字符串,num越大,创建str对象越多,内存消耗越大;
注:如有错误,请指正。