python小函数技巧积累

本文介绍了Python中格式化输出的方法及生成器的使用技巧。通过format函数可以更灵活地控制字符串输出格式,同时展示了如何利用yield关键字创建迭代器。

preface:在前进的路上遇到的Python各种小函数技巧积累。

enumerate:枚举

format:格式化输出。

对字符串进行输出时,print加逗号可破,但当字符串变量多了起来的时候,同字符串常量放在一起,逗号就变多了。不太方便。通过format类进行格式化,将变量都放在一起,能够更加方便地控制输出格式。具体的fomat语法说明网上博客也是一大堆,如http://www.2cto.com/kf/201312/262068.html,稍微提到的一些。当然,还有最重要的官网的资料的了:https://docs.python.org/2/library/string.html。都可以参考参考。

[python]  view plain  copy
  1. age = 25  
  2. name = 'Caroline'  
  3. print('{0} is {1} years old. '.format(name, age)) #输出参数  
  4. print('{0} is a girl. '.format(name))  
  5. print('{0:.3} is a decimal. '.format(1.0/3)) #小数点后三位  
  6. print('{0:_^11} is a 11 length. '.format(name)) #使用_补齐空位  
  7. print('{first} is as {second}. '.format(first=name, second='Wendy')) #别名替换  
  8. print('My name is {0.name}'.format(open('out.txt''w'))) #调用方法  
  9. print('My name is {0:8}.'.format('Fred')) #指定宽度  
  10. drinks={"coffee","tea","milk","water"}  
  11. for index,drink in enumerate(drinks):  
  12.     s="item: "+str(index)+" is "+drink  
  13.     print s  
  14.     print "item:",index,"is",drink  
  15.     print "item: {} is {} ".format(index,drink)  

yield:产生器

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. def fib_generator():  
  2.     a=0  
  3.     b=1  
  4.     while True:  
  5.         yield a  
  6.         a,b=b,a+b  
  7.   
  8. min_number=100  
  9. print fib_generator()  
  10. for number in fib_generator():  
  11.     print number  
  12.     if number > min_number:  
  13.         print number,min_number  
  14.         break  
  15. <generator object fib_generator at 0x0000000002173090>  
  16. 0  
  17. 1  
  18. 1  
  19. 2  
  20. 3  
  21. 5  
  22. 8  
  23. 13  
  24. 21  
  25. 34  
  26. 55  
  27. 89  
  28. 144  
  29. 144 100  
可以看出,带有yield的函数,具有迭代能力,是一个迭代器。以前遇到过,当数据量大了起来的时候,就变得很有用了。具体参考:http://www.ibm.com/developerworks/cn/opensource/os-cn-python-yield/,没仔细找到官网的介绍。

还有一些小技巧参考:https://www.airpair.com/python/posts/python-tips-and-traps.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值