def sum_list(*a):
#把所有参数值做累加
return sum(a)
print(sum_list(1,4,6,4))
import string
def count(*s):
#可变参数是字符串,统计所有字母个数
result=0
for i in s:
for j in i:
if j in string.ascii_letters:
result+=1
return result
print(count("efe","ef1e4d"))
def add(**kwargs):
print(kwargs)
print(type(kwargs))
print(add(a=1,b=2,c=3,d=4))
#for k,v in kw.itmes():
# print(k,v)
#把可变参数的value值进行累加
def add1(a,b,c=100,*args,**kwargs):
result = a+b
for i in args:
result+=i
for k,v in kwargs.items():
result+=v
return result
print(add1(1,2,3,4,5,6,m=10,n=100))
1.lamda函数(匿名函数)
>>> a=lambda x:x+2
>>> a(3)
5
>>> b=lambda x,y,z:x+y*z
>>> b(1,2,3)
7
>>> c=lambda :1
>>> c()
1
def make_reprater(n):
return lambda s:s*n
twice=make_reprater(2) #twice=lambda s:s*2
print(twice("word")) #word*2
print(twice(5)) #10*2
list_a=[lambda a:a**3,lambda b:b**3]
print(list_a[0])
g=list_a[0] #g=lambda a:a**3
print(g(2)) #2**3
2.repr函数(取得对象的字符串形式)
>>> a=3
>>> repr(a)
'3'
3.type函数
4.map函数
>>> map(str,[1,2,3,4]) #map(函数名,可迭代对象) 讲可迭代对象中每一个元素传给函数
<map object at 0x000001C1DE15FF88> #返回一个可迭代对象
>>> list(map(str,[1,2,3,4])) #需要list一下才能显示
['1', '2', '3', '4']
>>> "".join(list(map(str,[1,2,3,4])))
'1234'
#把字符串中数字字符转换为int
>>> list(map(int,"123"))
[1, 2, 3]
>>> for i in map(int,"123"):print(i)
...
1
2
3
def get_num(s):
"""将数字字符串转换数字类型,字母不变"""
result=[]
for i in s:
if i>="0" and i<="9":
return int(i)
else:
return s
print(list(map(get_num,"34ef65gsr7")))
#结果:
#[3, 4, 'e', 'f', 6, 5, 'g', 's', 'r', 7]
res=map(lambda x,y:(x**y,x+y),[2,4,6],[3,2,1])
for i in res:print(i)
#结果:
"""
(8, 5)
(16, 6)
(6, 7)
"""
5.filter函数
def func(s):
if s>="a" and s<="z":
return True
else:
return False
print(list(filter(func,"aabbDFEdf")))
#结果:
#['a', 'a', 'b', 'b', 'd', 'f']
#[100,2,4,231,656,32]讲大于100的数字取出
def funs(s):
if s>=100:
return True
else:
return False
print(list(filter(funs,[100,2,4,231,656,32])))
>>> def func(s):
... if s>="a" and s<="z":
... return True
... else:
... return False
...
...
>>> print (list(map(func,"aabbDef")))
[True, True, True, True, False, True, True]
>>> print (list(filter(func,"aabbDef")))
['a', 'a', 'b', 'b', 'e', 'f']
6.reduce函数
for functools import reduce
lst=[1,2,3,4,5]
print(reduce(lambda x,y:x+y,lst))
#结果:15
"""
1:1
2:1+2=3
3:3+3=6
4:6+4=10
5:10+5
"""
from functools import reduce
lst = [1,2,3,4,5]
print (reduce(lambda x,y:x+y,lst,100))#第三个参数相当于x初始值
#结果:115
#coding=utf-8
from functools import reduce
def fn(x, y):
return x * 10 + y
def char2num(s):
return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
#return int(s)
print(reduce(fn, map(char2num, '13579')))
# 1:1*10+3 =13
# 2:13*10+5=135
# 3:135*10+7=1357
# 4:1357*10+9 =13579
7.递归
(1)函数体里有自己调用自己的情况
(2)一点要有结束调用自己的条件
(3)除了最后结束调用自己,所有执行的调用过程是一样的,参数可能不一样
(4)语法规则:代码从上向下执行,如果遇到函数调用则停止向下执行,等待函数调用结果,有结果后在继续执行。
#正序输出1,2,3,4,5
def func(s):
if s>=2:
func(s-1)
print(s)
func(5)
#逆序输出:5,4,3,2,1
def func(s):
if s<5:
func(s+1)
print(s)
func(1)
8.exec():没有返回值
>>> s="a=1"
>>> a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>> exec(s)
>>> a
1
>>> command=input("输入名字:")
输入名字:print("hello")
>>> command
'print("hello")'
>>> exec(command)
hello
>>> def print_name(name):
... print (name)
...
>>> command=input("输入名字:")
输入名字:print_name("lily")
>>> exec(command)
lily
关键字驱动
数据驱动的特点:程序不变、数据变!
关键字驱动的特点:程序变化(调用不同的函数),数据也变化!
混合的:数据驱动加关键字驱动
def print_info(name,gender):
print("your name is %s and gender is %s" %(name,gender) )
def print_book(book_name,author):
print("book name is %s and author is %s" %(book_name,author))
fp=open("e:\\b.txt")
for i in fp:
func = i.split("||")[0]
name = i.split("||")[1]
gender = i.split("||")[2].strip()
command = "%s('%s','%s')" %(func,name,gender)
exec(command)
fp.close()
数据驱动:
fp=open("e:\\c.txt")
for i in fp:
name=i.strip()
print(i)
fp.close()
9.eval():有执行语句的返回值,但是不能执行赋值操作
>>> result=exec("a=len([1,2,3])")
>>> a
3
>>> result
>>> print(result)
None
>>> result=eval("a=len([1,2,3])") #不支持赋值
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1
a=len([1,2,3])
^
SyntaxError: invalid syntax
>>> result=eval("len([1,2,3])")
>>> print(result)
3
10.python没有重载:
不分类型、不定参数数量可以用默认值实现
练习:
#传入一个数和list,如果list中存在两者之和等于数,返回两者的坐标,存在返回None
def get_sum_num(n,l):
for i in range(len(l)):
for j in range(i+1,len(l)):
if l[i]+l[j]==n:
return i,j
return None
print(get_sum_num(100,[46,66,77,97,1,5]))
print(get_sum_num(100,[46,66,77,97,1,3]))