python6
高阶函数
内置的高阶函数
map
reduce
reduce(f,[1,2,3,4]) === > add(add(add(1,2),3),4)
reduce(cheng,range(1,11))
** 求10的阶乘:
- filter
In [15]: def is_oushu(n):
….: if n%2 == 0:
….: return True
….: else:
….: return False
….:
In [16]: filter(is_oushu,range(1,11))
Out[16]: [2, 4, 6, 8, 10]
- sorted()
n [20]: l = ["a","Ab","cd","C"]
In [21]: sorted(l)
Out[21]: ['Ab', 'C', 'a', 'cd']
In [22]: def cmp_ignore_case(s1,s2):
....: s1 = s1.lower()
....: s2 = s2.lower()
....: if s1 < s2:
....: return -1
....: elif s1 > s2:
....: return 1
....: else:
....: return 0
....:
In [23]: sorted(l,cmp_ignore_case)
Out[23]: ['a', 'Ab', 'C', 'cd']
# python的高级特性
切片
- 字符串,列表,元组是有序的序列,可以执行切片操作;
- 集合和字典是无序的,不能通过下标进行切片;
s[m:n:x]
迭代
- 迭代: 遍历目标变量中的每一个元素的过程; 只要可以通过for循环遍历的对象都是可迭代,可迭代对象通过for循环遍历;
from collections import Iterable
In [10]: isinstance(1,int)
Out[10]: True
In [11]: isinstance(1,Iterable)
Out[11]: False
In [12]: isinstance("hello",Iterable)
Out[12]: True
In [13]: isinstance({},Iterable)
Out[13]: True
In [14]: isinstance({"a":"1"},Iterable)
Out[14]: True
In [15]: isinstance({1,2,3},Iterable)
Out[15]: True
- 默认情况下,字典遍历是遍历字典的key值;
In [16]: d = {"ftp":21,"ssh":22}
In [17]: for i,j in d.items():
....: print i,j
....:
ftp 21
ssh 22
In [18]: for i in d:
....: print i
....:
ftp
ssh
In [21]: for host,port in [("server1",80),("server2",8080)]:
print host + ":" + str(port)
....:
server1:80
server2:8080
列表生成式
- 生成列表的一个式子;list comprehension.
格式: [i.lower() for i in l]
简单的列表生成式
[i**2 for i in range(1,10)]
[abs(i) for i in range(1,10)]
[fun(i) for i in range(1,11)]嵌套if语句
[i for i in range(1,10) if isprime(i)]嵌套for循环
“abc” “123”
[i+j for i in “abc” for j in “123”]
[service+”:”+str(port) for service,port in d.items()]
练习:
l = [“linux”,18,”red”],将所有的字符串变成大写并输出;
[i.upper() for i in l if isinstance(i,str)]
[i.upper() for i in l if type(i)==str]
生成器
通过列表生成式可以修改为生成器;
优势:
1). 节省内存空间;
2). 可以一边循环一边计算;
生成器的创建
1). 通过列表生成式可以修改为生成器;
2). 关键字yield,函数中有yield时,这个函数执行返回结果是一个生成器;生成器的查看:
1). g.next()
2). for循环
函数式编程
内置的高阶函数
map函数,map(函数, 序列),将传入的函数作用于列表中的每一个元素,返回一个列表;
reduce函数,reduce(函数, 序列),将函数的执行结果相加.
reduce(f,range(1,11)) = f(f(f(1,2),3),4)filter函数,filter(函数, 序列),将函数作用于序列的每一个元素,将满足条件的返回;
sorted函数,sorted(序列,函数),按照自定义格式排序;
输入一个正整数n,求n!(即阶乘)末尾0的个数
count=0
zero=0 #变量zero记录0的个数
def caculate(num):
global count,zero
for i in range(1,num):
count=num/(5**i)
zero+=count
if count==0:
return zero
n=input("please input n:")
print caculate(n)
函数实质是一个变量,fun -> 内存空间; func1 = fun; func1()
高阶函数:可以接受函数作为参数,或者把函数作为返回值的函数;
def fun1(var):
return var
def fun1(fun2):
…..
return fun2
In [1]: abs(-1)
Out[1]: 1
In [2]: a(-1)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-2-c976f5e459ea> in <module>()
----> 1 a(-1)
NameError: name 'a' is not defined
In [3]: a = abs
In [4]: a(-1)
Out[4]: 1
面向对象编程
- 面向过程编程:
- 面向对象编程(OOP) Object Oriented Programming
- 面向函数编程:(lisp)
(13+10)*2-10
a = 13+10
b = a*2
c = b-10
result = jian(multi(add(13,10),2),10)
练习
队列
#!/usr/bin/env python
#coding:utf-8
class Queue(object):
def __init__(self,queue):
print "queue is creating..."
self.queue = queue
def enqueue(self,item):
self.queue.append(item)
def manyEnQueue(self,*args):
self.queue.extend(args)
def outqueue(self):
if not self.queue == []:
return self.queue.pop(0)
else:
return None
def show(self):
for i in self.queue:
print i,
def head(self):
if not self.queue == []:
return self.queue[0]
else:
return None
def tail(self):
if not self.queue == []:
return self.queue[-1]
else:
return None
def length(self):
return len(self.queue)
def isEmity(self):
return self.queue == []
def __del__(self):
print "queue is deleteing..."
q1 = Queue([])
q1.enqueue(2)
q1.manyEnQueue(1,2,3,4)
q1.outqueue()
q1.show()
栈
#!/usr/bin/env python
#coding:utf-8
class Stack(object):
def __init__(self,stack):
self.stack = stack
def push(self,item):
self.stack.append(item)
def manyPush(self,*args):
self.stack.extend(args)
def pop(self):
self.stack.pop(-1)
def stack_top(self):
if not self.stack == []:
return self.stack[-1]
else:
return None
def show(self):
for i in self.stack:
print i,
def length(self):
return len(self.stack)
def isEmity(self):
return self.stack == []
def __del__(self):
print "stack is delet..."
s1 = Stack([])
s1.push(1)
s1.manyPush(1,2,3,4)
s1.pop()
s1.show()
上一篇: input限制输入长度
下一篇: 分支和循环练习