10个应该早点知道的Python技巧

时间:2022-04-26
本文章向大家介绍10个应该早点知道的Python技巧,主要内容包括1. 在Python 2中Python 3风格的打印输出、2. 枚举(list)、3.连续比较操作、4. collections.Counter、5. 字典解析、6. 用subprocess执行shell命令、7. dict .get() 和 .iteritems() 方法、8. Tuple拆包切换变量、9. 内省工具、10. PEP-8 兼容字符串链、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

我的这一生都在编程,但是我没有成为一名程序员。最初,我的大部分工作都是用Visual Basic来完成的,还包括一些其它语言工具,比如R语言,C语言、JavaScript等,这样实现起来最令人满意。几年前,我决定只用Python以至于我能提高自己到编程水平。我喜欢去解决问题,而不是重复的造轮子,这样子不需要考虑太多的事情。用Python去解决问题的效率真的非常高,解决了我一直在做的一些棘手的问题,多次出现了‘啊哈’灵机一动的瞬间。这里列出了10个Python技巧,如果我早点掌握它们,足以让我的生活更加轻松!

这里也有个IPython notebook nbviewer 版本的可供参考。

1. 在Python 2中Python 3风格的打印输出

让我对专注于Python的一件事时Python 2 和 Python 3的版本问题,最终,我选择了Python 2,因为我所需要使用的所有库在Python 3中并不全部兼容,如果我要使用Python 3的话,我需要幸幸苦苦的去调整我的代码。

不过说真的,在每天的编程中两个版本之间的最大不同就是打印输出和除法表达式。现在,我从future包中导入这两个函数,这样就可以使用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

Oh,这里有个给C程序员的彩蛋:

from __future__ import braces

输出:

  File "<ipython-input-3-2aebb3fc8ecf>", line 1
    from __future__ import braces
SyntaxError: not a chance

2. 枚举(list)

很明显,你应该能够在同一时间遍历列表和索引。但是,因为时间太长,我使用counter变量或者slice。

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

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

输出:

0 It's
1 only
2 a
3 model

3.连续比较操作

因为我习惯了静态语言的语法,其中的这种用法的语意是模糊的,我从来没有遇到将两个操作符放在同一表达式中。在许多的语言中,4 > 3 > 2将会返回False,因为(4>3)将会被看作一个布尔值(True),而True>2等同于False。在Python中,我了解到这种结构属于“语法糖”类别。

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! 

4. collections.Counter

集合库可以说是最棒的东西。Stackoverflow是我很早就知道了有序字典,但是我仍然使用一段代码来创建一个字典来统计事件发生的次数。有一天,我发现了collections.deque的一个用法。

from collections import Counter
from random import randrange
import pprint
mycounter = Counter()
for i in range(100):
    random_number = randrange(10)
    mycounter[random_number] += 1
for i in range(10):
    print(i, mycounter[i])

输出:

0 10
1 10
2 13
3 6
4 6
5 11
6 10
7 14
8 12
9 8

5. 字典解析

成为Python程序员的仪式是对list的理解,但是,我最终意识到对字典的理解一样有用,特别是逆转字典。

my_phrase = ["No", "one", "expects", "the", "Spanish", "Inquisition"]
my_dict = {key: value for value, key in enumerate(my_phrase)}
print(my_dict)
reversed_dict = {value: key for key, value in my_dict.items()}
print(reversed_dict)

输出:

{'Inquisition': 5, 'No': 0, 'expects': 2, 'one': 1, 'Spanish': 4, 'the': 3}
{0: 'No', 1: 'one', 2: 'expects', 3: 'the', 4: 'Spanish', 5: 'Inquisition'}

6. 用subprocess执行shell命令

过去,我经常使用os库来操作文件,现在,可以编程调用复杂的命令工具,比如编辑视频的ffmpeg工具。结合特定的subprocess和os库效果更好。

import subprocess
output = subprocess.check_output('dir', shell=True)
print(output)

输出:

 Volume in drive C is OS
 Volume Serial Number is [REDACTED]
 Directory of C:UsersDavidDocuments[REDACTED]

2014-11-26  06:04 AM    <DIR>          .
2014-11-26  06:04 AM    <DIR>          ..
2014-11-23  11:47 AM    <DIR>          .git
2014-11-26  06:06 AM    <DIR>          .ipynb_checkpoints
2014-11-23  08:59 AM    <DIR>          CCCma
2014-09-03  06:58 AM            19,450 colorbrewdict.py
2014-09-03  06:58 AM            92,175 imagecompare.ipynb
2014-11-23  08:41 AM    <DIR>          Japan_Earthquakes
2014-09-03  06:58 AM             1,100 LICENSE
2014-09-03  06:58 AM             5,263 monty_monte.ipynb
2014-09-03  06:58 AM            31,082 pocket_tumblr_reddit_api.ipynb
2014-11-26  06:04 AM             3,211 README.md
2014-11-26  06:14 AM            19,898 top_10_python_idioms.ipynb
2014-09-03  06:58 AM             5,813 tree_convert_mega_to_gexf.ipynb
2014-09-03  06:58 AM             5,453 tree_convert_mega_to_json.ipynb
2014-09-03  06:58 AM             1,211 tree_convert_newick_to_json.py
2014-09-03  06:58 AM            55,970 weather_ML.ipynb
              11 File(s)        240,626 bytes
               6 Dir(s)  180,880,490,496 bytes free

7. dict .get() 和 .iteritems() 方法

当一个键不存在时有一个默认值有很多用处,就比如lists的enumerate(),可以在字典中遍历key和value。

my_dict = {'name': 'Lancelot', 'quest': 'Holy Grail', 'favourite_color': 'blue'}

print(my_dict.get('airspeed velocity of an unladen swallow', 'African or European?n'))

for key, value in my_dict.iteritems():
    print(key, value, sep=": ")

输出:

African or European?

quest: Holy Grail
name: Lancelot
favourite_color: blue

8. Tuple拆包切换变量

您知道有多少次,在VB中我必须得用第三个临时变量?c = a; a = b; b = c?

a = 'Spam'
b = 'Eggs'

print(a, b)

a, b = b, a

print(a, b)

输出:

Spam Eggs
Eggs Spam

9. 内省工具

我知道dir(),但是我曾以为作为IPython的魔法命令help()会做同样的事情,它有更多的方式。(在从reddit的 /r/python获得了大量好的建议后,这篇文章已经更新了,确实,我多么希望之前我就知道了的)

my_dict = {'That': 'an ex-parrot!'}

help(my_dict)

输出:

Help on dict object:

class dict(object)
 |  dict() -> new empty dictionary
 |  dict(mapping) -> new dictionary initialized from a mapping object's
 |      (key, value) pairs
 |  dict(iterable) -> new dictionary initialized as if via:
 |      d = {}
 |      for k, v in iterable:
 |          d[k] = v
 |  dict(**kwargs) -> new dictionary initialized with the name=value pairs
 |      in the keyword argument list.  For example:  dict(one=1, two=2)
 |  
 |  Methods defined here:
 |  
 |  __cmp__(...)
 |      x.__cmp__(y) <==> cmp(x,y)
 |  
 |  __contains__(...)
 |      D.__contains__(k) -> True if D has a key k, else False
 |  
 |  __delitem__(...)
 |      x.__delitem__(y) <==> del x[y]
 |  
 |  __eq__(...)
 |      x.__eq__(y) <==> x==y
 |  

[TRUNCATED FOR SPACE]

 |  
 |  update(...)
 |      D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
 |      If E present and has a .keys() method, does:     for k in E: D[k] = E[k]
 |      If E present and lacks .keys() method, does:     for (k, v) in E: D[k] = v
 |      In either case, this is followed by: for k in F: D[k] = F[k]
 |  
 |  values(...)
 |      D.values() -> list of D's values
 |  
 |  viewitems(...)
 |      D.viewitems() -> a set-like object providing a view on D's items
 |  
 |  viewkeys(...)
 |      D.viewkeys() -> a set-like object providing a view on D's keys
 |  
 |  viewvalues(...)
 |      D.viewvalues() -> an object providing a view on D's values
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __hash__ = None
 |  
 |  __new__ = 
 |      T.__new__(S, ...) -> a new object with type S, a subtype of T

10. PEP-8 兼容字符串链

PEP8 是Python编程风格指南。除其他事项外,它建议每一行不要超过80个字符,并且保持换行缩进一致。

可以用反斜线、括号与逗号、以及‘+’操作符来实现,但是这些用来处理多行字符串就会显得很笨拙。有一个多行字符串写法,三重引号,但是它不允许在换行时缩进一致。

有一个解决方法:没有逗号的括号。我不知道为什么这样也会有效,但是为它有效而高兴。

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!")
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://prooffreaderplus.blogspot.com/2014/11/top-10-python-idioms-i-wished-id.html