笔记整理----python(2)

1、lambda表达式建立一个匿名函数并返回一个函数对象

g=lambda x:x**2

上述语句建立了一个匿名函数返回一个函数对象给g,参数是x,函数的返回值为x的平方。

2、reduce(函数,列表,初始化器),将函数作用于列表上的每个元素。这个函数必须有两个参数,第一次选择列表中的前两个元素执行这个函数,之后,每次取一个值,与上一次计算了的值再次作为参数传递进这个函数然后执行,直到最后一个元素。如果要是列表中只有一个元素的话,那么就直接返回这个元素。如果第三个参数初始化器不是NONE,那么就以这个参数的值还有列表的第一个值作为第一次的计算开始向下进行。


reduce(function, iterable[, initializer]) 
Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). The left argument, x, is the accumulated value and the right argument, y, is the update value from the iterable. If the optional initializer is present, it is placed before the items of the iterable in the calculation, and serves as a default when the iterable is empty. If initializer is not given and iterable contains only one item, the first item is returned. Roughly equivalent to:

def reduce(function, iterable, initializer=None):
    it = iter(iterable)
    if initializer is None:
        try:
            initializer = next(it)
        except StopIteration:
            raise TypeError('reduce() of empty sequence with no initial value')
    accum_value = initializer
    for x in it:
        accum_value = function(accum_value, x)
    return accum_value

上面是英文文档,写的很清楚。

3、一般来说,如果我们编写一个模块来测试把它当做一个程序来执行的时候,那么此时的命名空间为main,如果单单的只是模块的导入的话,那么这个模块的命名空间就是它保存Py文件的文件名。

如此,我们就将测试代码也写在模块内部。加上如下代码

def ceshi():
        print "fdsfs"

if __name__ == '__main__':
        ceshi()

如果是直接用解释器执行这个模块,那么表示当前主程序正在调用这个模块中的内容,所以会直接执行ceshi这个函数。如果是Import ceshi,那么他的命名空间就是ceshi,便不会执行。
if __name__ == '__main__':
        ceshi()



4、在一个放置了很多单独模块的py文件的文件夹下,创建一个__init__.py的文件,即这个文件就会变成为一个包结构。


5、可以用import 模块名 as 别名,来给你导入的模块起一个别的名字,便于你的调用。


6、capitalize()将字符串的首字母变大写


7、replace(old, new, x)这是字符串函数,用new替换old,x表示替换的次数。


8、filter(函数,序列),这个函数的作用是,将序列的每个元素依次送入这个函数中,如果这个函数返回的是真值,那么就把这个元素留下,否则就过滤掉。如果这个函数没有被指定,只是单纯的filter(序列),那么就会过滤掉序列中的值为假的元素。filter将会返回一个过滤后的列表。


9、

a = zip([1,2,3], [4,5,6])
print a
zip将每个列表对应的元素组成一个元组,然后返回一个以元组为元素的列表,如果列表的长短不一,那么以最短的列表作为标准来遍历。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值