[150808]十个我希望早点知道的Python方法

Python 是一种面向对象、解释型计算机程序设计语言,由Guido van Rossum于1989年底发明,第一个公开发行版发行于1991年,Python 源代码同样遵循 GPL(GNU General Public License)协议。Python语法简洁而清晰,具有丰富和强大的类库。

在Python 2中使用Python 3式的输出
Python 2与Python 3不兼容,这让我不知道该选择哪个版本的Python。最终我选择了Python 2,因为当时许多我需要用的库都与Python 3不兼容。

但实际上,日常使用中最大的版本差异是输出(print)和除法行为。现在我在Python 2的代码中都用import from future来导入Python 3的输出和除法。现在我用到的几乎所有库都支持Python 3,因此会很快迁移到Python 3中。
Python代码
  1. mynumber = 5  
  2.   
  3. print "Python 2:"  
  4. print "The number is %d" % (mynumber)  
  5. print mynumber / 2,  
  6. print mynumber // 2  
  7.   
  8. from __future__ import print_function  
  9. from __future__ import division  
  10.   
  11. print('nPython 3:')  
  12. print("The number is {}".format(mynumber))  
  13. print(mynumber / 2, end=' ')  
  14. print(mynumber // 2)  
  15.   
  16. 输出:  
  17. Python 2:  
  18. The number is 5  
  19. 2 2  
  20.   
  21. Python 3:  
  22. The number is 5  
  23. 2.5 2  


enumerate(list)

很明显,迭代列表时,应该同时迭代其中的元素及其索引,但在很长一段时间内,我都尴尬的使用计数变量或切片。
Python代码
  1. mylist = ["It's", 'only', 'a', 'model']  
  2.   
  3. for index, item in enumerate(mylist):  
  4.     print(index, item)  
  5.   
  6. 输出:  
  7. 0 It's  
  8. 1 only  
  9. 2 a  
  10. 3 model  


链式比较操作符

由于我以前使用的是静态语言(在这些语言中该用法有二义性),从来没有将两个比较操作符放在一个表达式中。在许多语言中,4 > 3 > 2会返回False,因为4 > 3的结果是布尔值,而True > 2将得出False。
Python代码
  1. mynumber = 3  
  2.   
  3. if 4 > mynumber > 2:  
  4.     print("Chained comparison operators work! n" * 3)  
  5.   
  6. 输出:  
  7. Chained comparison operators work!  
  8. Chained comparison operators work!  
  9. Chained comparison operators work!  



十个我希望早点知道的python方法

youmai · 2015.08.05 · python · 阅读 3371


python
Python 是一种面向对象、解释型计算机程序设计语言,由Guido van Rossum于1989年底发明,第一个公开发行版发行于1991年,Python 源代码同样遵循 GPL(GNU General Public License)协议[1] 。Python语法简洁而清晰,具有丰富和强大的类库。
下载地址 官方主页
在Python 2中使用Python 3式的输出

Python 2与Python 3不兼容,这让我不知道该选择哪个版本的Python。最终我选择了Python 2,因为当时许多我需要用的库都与Python 3不兼容。

但实际上,日常使用中最大的版本差异是输出(print)和除法行为。现在我在Python 2的代码中都用import from future来导入Python 3的输出和除法。现在我用到的几乎所有库都支持Python 3,因此会很快迁移到Python 3中。

mynumber = 5

print "Python 2:"
print "The number is %d" % (mynumber)
print mynumber / 2,
print mynumber // 2

from __future__ import print_function
from __future__ import division

print('nPython 3:')
print("The number is {}".format(mynumber))
print(mynumber / 2, end=' ')
print(mynumber // 2)

输出:
Python 2:
The number is 5
2 2

Python 3:
The number is 5
2.5 2
enumerate(list)

很明显,迭代列表时,应该同时迭代其中的元素及其索引,但在很长一段时间内,我都尴尬的使用计数变量或切片。


mylist = ["It's", 'only', 'a', 'model']

for index, item in enumerate(mylist):
    print(index, item)

输出:
0 It's
1 only
2 a
3 model
链式比较操作符

由于我以前使用的是静态语言(在这些语言中该用法有二义性),从来没有将两个比较操作符放在一个表达式中。在许多语言中,4 > 3 > 2会返回False,因为4 > 3的结果是布尔值,而True > 2将得出False。

mynumber = 3

if 4 > mynumber > 2:
    print("Chained comparison operators work! n" * 3)

输出:
Chained comparison operators work!
Chained comparison operators work!
Chained comparison operators work!

collections.Counter

Python的集合库看上去是最好的。在计算需要集合中元素的个数时,StackOverflow找到的答案是创建有序字典,但我坚持使用一个代码片段来创建字典,计算结果中元素出现的频率。直到有一天,我发现可以用collections.deque。
Python代码
  1. from collections import Counter  
  2. from random import randrange  
  3. import pprint  
  4.   
  5. mycounter = Counter()  
  6.   
  7. for i in range(100):  
  8.     random_number = randrange(10)  
  9.     mycounter[random_number] += 1  
  10.   
  11. for i in range(10):  
  12.     print(i, mycounter[i])  
  13.   
  14. 输出:  
  15. 0 10  
  16. 1 10  
  17. 2 13  
  18. 3 6  
  19. 4 6  
  20. 5 11  
  21. 6 10  
  22. 7 14  
  23. 8 12  
  24. 9 8  


字典推导

Python开发者的一个重要标志就是理解列表推导,但最终我发现字典推导也很有用,特别是在交换字典的键和值的时候。
Python代码
  1. my_phrase = ["No""one""expects""the""Spanish""Inquisition"]  
  2. my_dict = {key: value for value, key in enumerate(my_phrase)}  
  3. print(my_dict)  
  4. reversed_dict = {value: key for key, value in my_dict.items()}  
  5. print(reversed_dict)  
  6.   
  7. 输出:  
  8. {'Inquisition'5'No'0'expects'2'one'1'Spanish'4'the'3}  
  9. {0'No'1'one'2'expects'3'the'4'Spanish'5'Inquisition'}  

用subprocess执行shell命令
Python代码
  1. import subprocess  
  2. output = subprocess.check_output('dir', shell=True)  
  3. print(output)  

注意,用os库完成这个特定命令比用subprocess更好。我只想有一个大家都熟悉的命令。同时,一般来说,在subprocess中使用shell=True参数是非常糟糕的主意,在这里使用这个参数仅仅是为了能在一个IPython notebook单元中放置命令的输出。不要自己使用这个参数!下面是用os模块执行shell命令。
Python代码
  1. import os  
  2. os.system('dir')  

注意,这里的dir命令会立刻在shell中输出,不能够保存到文件(变量)中,如果想要保存到变量中,可以使用popen:
Python代码
  1. import os  
  2. output = os.popen('dir')  
  3. print output.read()  

字典的.get()和.iteritems()方法

字典的get()方法可以设置默认值,当用get()查找的键不存在时,返回方法中的默认值参数是很有用的。与列表中的enumerate()相同,可以用键值元组迭代字典中的元素。
Python代码
  1. my_dict = {‘name’: ‘Lancelot’, ‘quest’: ‘Holy Grail’, ‘favourite_color’: ‘blue’}  
  2.   
  3. print(my_dict.get('airspeed velocity of an unladen swallow''African or European?n'))  
  4.   
  5. for key, value in my_dict.iteritems():  
  6.     print(key, value, sep=": ")  

输出:
Python代码
  1. African or European?  
  2.   
  3. quest: Holy Grail  
  4. name: Lancelot  
  5. favourite_color: blue  

如果要用for迭代输出字典,就要用到字典的iteritems()方法,这个方法在python3.x中已经废除了,取代的是items()方法,items()方法在python2.x中也存在

用于交换元素的元组解包

在VB中,每当需要交换两个变量时,都要用要一个愚蠢的临时变量:c = a; a = b; b = c
Python代码
  1. a = 'Spam'  
  2. b = 'Eggs'  
  3.   
  4. print(a, b)  
  5.   
  6. a, b = b, a  
  7. print(a, b)  
  8.   
  9. 输出:  
  10. Spam Eggs  
  11. Eggs Spam  

内省工具Introspection tools

我知道dir()方法,我本以为help()方法和IPython中的?魔法命令是一样的,但help()的功能更强大。
Python代码
  1. my_dict = {'That''an ex-parrot!'}  
  2.   
  3. help(my_dict)  

输出:
Python代码
  1. Help on dict object:  
  2.   
  3. class dict(object)  
  4.  | dict() -> new empty dictionary  
  5.  | dict(mapping) -> new dictionary initialized from a mapping object's  
  6.  | (key, value) pairs  
  7.  | dict(iterable) -> new dictionary initialized as if via:  
  8.  | d = {}  
  9.  | for k, v in iterable:  
  10.  | d[k] = v  
  11.  | dict(**kwargs) -> new dictionary initialized with the name=value pairs  
  12.  | in the keyword argument list. For example: dict(one=1, two=2)  
  13.  |  
  14.  | Methods defined here:  
  15.  |  
  16.  | __cmp__(...)  
  17.  | x.__cmp__(y) <==> cmp(x,y)  
  18.  |  
  19.  | __contains__(...)  
  20.  | D.__contains__(k) -> True if D has a key k, else False  
  21.  |  
  22.  | __delitem__(...)  
  23.  | x.__delitem__(y) <==> del x[y]  
  24.  |  
  25.  | __eq__(...)  
  26.  | x.__eq__(y) <==> x==y  
  27.  |  
  28.   
  29. [TRUNCATED FOR SPACE]  
  30.   
  31.  |   
  32.  | update(...)  
  33.  | D.update([E, ]**F) -> None. Update D from dict/iterable E and F.  
  34.  | If E present and has a .keys() method, does: for k in E: D[k] = E[k]  
  35.  | If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v  
  36.  | In either case, this is followed by: for k in F: D[k] = F[k]  
  37.  |  
  38.  | values(...)  
  39.  | D.values() -> list of D's values  
  40.  |  
  41.  | viewitems(...)  
  42.  | D.viewitems() -> a set-like object providing a view on D's items  
  43.  |  
  44.  | viewkeys(...)  
  45.  | D.viewkeys() -> a set-like object providing a view on D's keys  
  46.  |  
  47.  | viewvalues(...)  
  48.  | D.viewvalues() -> an object providing a view on D's values  
  49.  |  
  50.  | ----------------------------------------------------------------------  
  51.  | Data and other attributes defined here:  
  52.  |  
  53.  | __hash__ = None  
  54.  |  
  55.  | __new__ =  
  56.  | T.__new__(S, ...) -> a new object with type S, a subtype of T  

PEP-8兼容的字符串连接

PEP8是Python编码样式指南。撇开其他的不看,PEP8要求每行不能超过80个字符,超过的部分要换行并缩进。

可以通过反斜杠、带逗号“,”的圆括号“()”、或者额外的加号“+”来完成换行。但对于多行字符串,这些解决方案都不够优雅。Python有个多行字符串记号,即三个引号,但这样无法换行后保持缩进。

还有一个方法,那就是不带逗号的圆括号。我不知道为什么这种方式能工作,但能用就行。
Python代码
  1. my_long_text = ("We are no longer the knights who say Ni! "  
  2.                 "We are now the knights who say ekki-ekki-"  
  3.                 "ekki-p'tang-zoom-boing-z'nourrwringmm!")  
  4. print(my_long_text)  

输出:
引用

We are no longer the knights who say Ni! We are now the knights who say ekki-ekki-ekki-p'tang-zoom-boing-z'nourrwringmm!


文章来自:http://www.codefrom.com/c/214

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值