【Python学习记录】2015-02-17
来源:互联网 发布:共享经济 知乎 编辑:程序博客网 时间:2024/05/16 15:55
python函数的参数:
可变参数:
Python函数的参数是可以使用可变参数的.可变参数以一个list或tuple
def fun(*m):<span style="white-space:pre"></span>sum=0<span style="white-space:pre"></span>for n in m<span style="white-space:pre"></span>sum+=n<span style="white-space:pre"></span>return sum
fun(1,2,3)<span style="white-space:pre"></span># output: 6fun(2,5,6,9)<span style="white-space:pre"></span># output: 22l=[1,2,3,4]fun(*l)<span style="white-space:pre"></span># output: 10
关键字参数:
关键字参数允许传入带参数名的参数,这些关键字参数在函数内部形成一个dict
def fun(**kw):<span style="white-space:pre"></span>print kw
fun(name='xiaoming',age=7)<span style="white-space:pre"></span># output: {'name'='xiaoming','age'=7}d={'name'='xiaoming','age'=7}fun(**d)<span style="white-space:pre"></span># output: <span style="font-family: Arial, Helvetica, sans-serif;">{'name'='xiaoming','age'=7}</span>
参数定义的顺序必须是:必选参数、默认参数、可变参数和关键字参数。
生成器(generator)
我们知道,Python中允许有列表生成式([x*x for x in range(10)]). 但是有的时候当数据规模很大,我们可以考虑另一种形式:生成器.
生成器只需要把列表生成式的[ ]换成( )就可以实现,使用.next()方法可以依次取出元素.实际使用的时候,通常使用for来迭代.
g=(x*x for x in range(10))g.next()<span style="white-space:pre"></span># output: 1g.next()<span style="white-space:pre"></span># output: 4for x in g:<span style="white-space:pre"></span>print x<span style="white-space:pre"></span># output: 1 4 9 16 25 ...
另一种生成器的形式是函数生成器,函数中讲输出的位置换成yield.这个函数就变成了生成器,每次使用.next()方法的时候,都会执行到yield处停止,下次再调用.next()的时候,会从上次yield的位置继续执行. 同样,也可用for来迭代.
def fun(n):<span style="white-space:pre"></span>for x in range(n):<span style="white-space:pre"></span>yield x*xo=fun(10)o.next()<span style="white-space:pre"></span># output: 1o.next()<span style="white-space:pre"></span># output: 4<pre name="code" class="python">
</pre>for x in o:<span style="white-space:pre"></span>print x<span style="white-space:pre"></span># output: 1 4 9 16 25 ...
0 0
- 【Python学习记录】2015-02-17
- 【Python学习记录】2015-02-06
- 【Python学习记录】2015-01-27
- 【Python学习记录】2015-01-28
- 【Python学习记录】2015-01-29
- python学习记录
- Python 学习记录1
- python学习记录
- Python学习记录2
- Python学习记录
- python学习记录
- python学习记录
- Python学习记录
- python学习记录
- Python学习记录
- Python学习记录
- python 学习记录1
- python学习记录
- 【JavaScript】原生态兼容IE6的图片轮播
- 6 clip 慢慢展开的图片
- HDU 1023 Train Problem II
- vector 实现邻接表
- java-职责链模式
- 【Python学习记录】2015-02-17
- NYOJ--36(动态规划)-题目----------------------------- 最长公共子序列
- (hdu step 4.2.3)Knight Moves(求从起点是否能够到达终点的最小步数)
- 害死人不偿命的(3n+1)猜想
- 写出这个数
- 2015.02.最新面试题总结(I)
- 我要通过!
- 成绩排名
- Java中的流,可以从不同的角度进行分类。