Python学习日记[3]

1、lambda函数

     lambda--匿名函数(不需要具体名称的函数)

     对于一些简单函数,可以省去函数定义的过程。

     对于使用的次数少的函数也可。

  

1 >>> test = lambda x: x+2
2 >>> test(1)
3 3

2、BIF(内建函数-built-in functions)

     

filter(function, sequence):对sequence中的item依次执行function(item),将执行结果为True的item组成一个List/String/Tuple(取决于sequence的类型)返回:
>>> def f(x): return x % 2 != 0 and x % 3 != 0 
>>> filter(f, range(2, 25)) 
[5, 7, 11, 13, 17, 19, 23]
>>> def f(x): return x != 'a' 
>>> filter(f, "abcdef") 
'bcdef'

>>> help(filter)

Help on built-in function filter in module __builtin__:


filter(...)
filter(function or None, sequence) -> list, tuple, or string

Return those items of sequence for which function(item) is true. If
function is None, return the items that are true. If sequence is a tuple
or string, return the same type, else return a list.

 

map(function, sequence) :对sequence中的item依次执行function(item),见执行结果组成一个List返回:
>>> def cube(x): return x*x*x 
>>> map(cube, range(1, 11)) 
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
>>> def cube(x) : return x + x 
... 
>>> map(cube , "abcde") 
['aa', 'bb', 'cc', 'dd', 'ee']
另外map也支持多个sequence,这就要求function也支持相应数量的参数输入:
>>> def add(x, y): return x+y 
>>> map(add, range(8), range(8)) 
[0, 2, 4, 6, 8, 10, 12, 14]

>>>help(map)

Help on built-in function map in module __builtin__:

map(...)
map(function, sequence[, sequence, ...]) -> list

Return a list of the results of applying the function to the items of
the argument sequence(s). If more than one sequence is given, the
function is called with an argument list consisting of the corresponding
item of each sequence, substituting None for missing values when not all
sequences have the same length. If the function is None, return a list of
the items of the sequence (or a list of tuples if more than one sequence).

 

  

reduce(function, sequence, starting_value):对sequence中的item顺序迭代调用function,如果有starting_value,还可以作为初始值调用,例如可以用来对List求和:
>>> def add(x,y): return x + y 
>>> reduce(add, range(1, 11)) 
55 (注:1+2+3+4+5+6+7+8+9+10)
>>> reduce(add, range(1, 11), 20) 
75 (注:1+2+3+4+5+6+7+8+9+10+20)

>>>help(reduce)

Help on built-in function reduce in module __builtin__:

reduce(...)
reduce(function, sequence[, initial]) -> value

Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.

    

lambda:这是Python支持一种有趣的语法,它允许你快速定义单行的最小函数,类似与C语言中的宏,这些叫做lambda的函数,是从LISP借用来的,可以用在任何需要函数的地方: 
>>> g = lambda x: x * 2 
>>> g(3) 
6 
>>> (lambda x: x * 2)(3) 
6

  

我们也可以把filter map reduce 和lambda结合起来用,函数就可以简单的写成一行。
例如
kmpathes = filter(lambda kmpath: kmpath,                  
map(lambda kmpath: string.strip(kmpath),
string.split(l, ':')))              
看起来麻烦,其实就像用语言来描述问题一样,非常优雅。
对 l 中的所有元素以':'做分割,得出一个列表。对这个列表的每一个元素做字符串strip,形成一个列表。对这个列表的每一个元素做直接返回操作(这个地方可以加上过滤条件限制),最终获得一个字符串被':'分割的列表,列表中的每一个字符串都做了strip,并可以对特殊字符串过滤。

 

  [转] http://hi.baidu.com/black/item/307001d18715fc322a35c747

3、递归,字典(略)……

4、集合set

    

>>> num = {}
>>> type(num)
<type 'dict'>#字典
>>> num2 = {1,2,4,5}
>>> type(num2)
<type 'set'>#集合

   无序性,唯一性,确定性

 

没有对[]重载

>>> num2[1]

Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    num2[1]
TypeError: 'set' object does not support indexing

创建一个集合

>>> num1 = {1,2,3,'a','v'}#用花括号
>>> type(num1)
<type 'set'>
>>> num3 = set(range(10))#set()工厂函数
>>> num3
set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

使用in 和 not in 判断元素是否存在于集合中

>>> 0 in num3
True
>>> 0 not in num2
True
>>> dir(set)
['__and__', '__class__', '__cmp__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__iand__', '__init__', '__ior__', '__isub__', '__iter__', '__ixor__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'add', 'clear', 'copy', 'difference', 'difference_update', 'discard', 'intersection', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update']

  frozen--不可变集合:

>>> num4 = frozenset(range(10))
>>> num4
frozenset([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> num3.add(1)
>>> num4.remove(0)

Traceback (most recent call last):
  File "<pyshell#32>", line 1, in <module>
    num4.remove(0)
AttributeError: 'frozenset' object has no attribute 'remove'

 5、文件操作

  1)文件操作方式

打开模式 执行操作
'r' 以只读方式打开(默认)
'w' 以写入方式打开,会覆盖已经写入的内容
'x' 如果文件已经存在,此方式会引发异常
'a' 以写入方式打开,如果文件存在,追加输入
'b' 以二进制模式打开  
't' 以文本模式打开(默认)
'+' 可读写模式(可添加到其他模式使用)
'U' 通用换行符支持

 

 

 

 

 

 

 

>>> f = open('D:\\test.txt')
>>> f.read()
'sfklsdhjgkfhgsdsaklfjgdsaa\nsabjfsdaghkjfgdkA\t'

  

>>> dir(file)
['__class__', '__delattr__', '__doc__', '__enter__', '__exit__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'closed', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'mode', 'name', 'newlines', 'next', 'read', 'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines', 'xreadlines']

 2)OS_module(系统模块)

   

posted on 2015-01-25 11:34  joker_02  阅读(132)  评论(0编辑  收藏  举报

导航