枚举

之前这样操作:

i = 0for item in iterable:  print i, item  i += 1

现在这样操作:

for i, item in enumerate(iterable):  print i, item

enumerate函数还可以接收第二个参数。就像下面这样:

>>> list(enumerate('abc')) [(0, 'a');
(1, 'b');
(2, 'c')]  >>> list(enumerate('abc', 1)) [(1, 'a');
(2, 'b');
(3, 'c')]

字典/集合 解析

你也许知道如何进行列表解析 但是可能不知道字典/集合解析。它们简单易用且高效。就像下面这个例子:

my_dict = {i: i * i for i in xrange(100)} my_set = {i * 15 for i in xrange(100)} # There is only a difference of ':' in both # 两者的区别在于字典推导中有冒号

强制浮点除法

如果除以一个整数 即使结果是一个浮点数 Python 2(校注 这里我添上了版本号)依旧会给一个整数。为了规避这个问题 需要这样做:

result = 1.0/2

但是现在有一种别的方法可以解决这个问题 甚至在之前我都没有意识到有这种方法存在。你可以进行如下操作:

from __future__ import division result = 1/2# print(result)# 0.5

瞧 现在你不需要在数据上附件".0" 来获得准确答案了。需要注意的是这个窍门只适用于Python 2。在Python 3 中就不需要进行import 操作了 因为它已经默认进行import了。

简单服务器

你是否想要快速方便的共享某个目录下的文件呢?你可以这么做:

# Python2python -m SimpleHTTPServer# Python 3python3 -m http.server

这样会为启动一个服务器。

对Python表达式求值

都知道eval函数 但是知道literal_eval函数么?也许很多人都不知道吧。可以用这种操作:

import ast my_list = ast.literal_eval(expr)

来代替以下这种操作:

expr = "[1, 2, 3]"my_list = eval(expr)

我相信对于大多数人来说这种形式是第一次看见 但是实际上这个在Python中已经存在很长时间了。

脚本分析

你可以很容易的通过运行以下代码进行脚本分析:

python -m cProfile my_script.py

对象自检

在Python 中你可以通过dir() 函数来检查对象。正如下面这个例子:

>>> foo = [1, 2, 3, 4]>>> dir(foo) ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', ... , 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

调试脚本

你可以很方便的通过pdb模块在你的脚本中设置断点。正如下面这个例子:

import pdbpdb.set_trace()

你可以在脚本的任何地方加入pdb.set_trace() 该函数会在那个位置设置一个断点。

if 结构简化

如果你需要检查几个数值你可以用以下方法:

if n in [1,4,5,6]:

来替代下面这个方式:

if n==1 or n==4 or n==5 or n==6:

字符串/数列 逆序

你可以用以下方法快速逆序排列数列:

>>> a = [1,2,3,4]>>> a[::-1][4, 3, 2, 1] # This creates a new reversed list. # If you want to reverse a list in place you can do: a.reverse()

这总方式也同样适用于字符串的逆序:

>>> foo = "yasoob">>> foo[::-1]'boosay'

优美地打印

你可以通过以下方式对字典和数列进行优美地打印:

from pprint import pprint pprint(my_dict)

这种方式对于字典打印更加高效。此外 如果你想要漂亮的将文件中的json文档打印出来 你可以用以下这种方式:

cat file.json | python -m json.tool

三元运算

三元运算是if-else 语句的快捷操作 也被称为条件运算。这里有几个例子可以供你参考 它们可以让你的代码更加紧凑 更加美观。

[on_true] if [expression] else [on_false]x, y = 50, 25small = x if x < y else y
 ','0');('948','950','

不久前 在互联网上出现了一篇有趣的文章 讲的是对于同一个问题 不同层次的程序员编出的 Python 代码显示出了不同的风格 代码都很简单 有趣。

编程新手

def factorial(x):  if x == 0:    return 1  else:    return x * factorial(x - 1)print factorial(6)

一年编程经验(学 Pascal 的)

def factorial(x):  result = 1  i = 2  while i <= x:    result = result * i    i = i + 1  return resultprint factorial(6)

一年编程经验(学 C 的)

def fact(x): #{  result = i = 1;  while (i <= x): #{    result *= i;    i += 1;  #}  return result;#}print(fact(6))

一年编程经验(读过 SICP)

@tailcalldef fact(x, acc=1):  if (x > 1): return (fact((x - 1);
(acc * x)))  else: return accprint(fact(6))

一年编程经验(Python)

def Factorial(x):  res = 1  for i in xrange(2, x + 1):    res *= i  return resprint Factorial(6)

懒惰的 Python 程序员

def fact(x):  return x > 1 and x * fact(x - 1) or 1print fact(6)

更懒的 Python 程序员

f = lambda x: x and x * f(x - 1) or 1print f(6)

Python 专家

import operator as opimport functional as ffact = lambda x: f.foldl(op.mul, 1, xrange(2, x + 1))print fact(6)

Python 黑客

import sys@tailcalldef fact(x, acc=1):  if x: return fact(x.__sub__(1), acc.__mul__(x))  return accsys.stdout.write(str(fact(6)) + '_mg_newline_mg_')

专家级程序员

import c_mathfact = c_math.factprint fact(6)

大英帝国程序员

import c_mathsfact = c_maths.factprint fact(6)

Web 设计人员

def factorial(x):  #-------------------------------------------------  #--- 这段代码是从 Math Vault 那弄过来滴---  #--- 计算阶乘 (C)亚瑟·史密斯 1999年---  #-------------------------------------------------  result = str(1)  i = 1 #谢谢亚当  while i <= x:    #result = result * i #It's faster to use *=    #result = str(result * result + i)      #result = int(result *= i) #??????    result str(int(result) * i)    #result = int(str(result) * i)    i = i + 1  return resultprint factorial(6)

Unix 程序员

import osdef fact(x):  os.system('factorial ' + str(x))fact(6)

Windows 程序员

NULL = Nonedef CalculateAndPrintFactorialEx(dwNumber,                 hOutputDevice,                 lpLparam,                 lpWparam,                 lpsscSecurity,                 *dwReserved):  if lpsscSecurity != NULL:    return NULL #Not implemented  dwResult = dwCounter = 1  while dwCounter <= dwNumber:    dwResult *= dwCounter    dwCounter += 1  hOutputDevice.write(str(dwResult))  hOutputDevice.write('_mg_newline_mg_')  return 1import sysCalculateAndPrintFactorialEx(6, sys.stdout, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)

企业级程序员

def new(cls, *args, **kwargs):  return cls(*args, **kwargs) class Number(object):  pass class IntegralNumber(int, Number):  def toInt(self):    return new (int, self) class InternalBase(object):  def __init__(self, base):    self.base = base.toInt()   def getBase(self):    return new (IntegralNumber, self.base) class MathematicsSystem(object):  def __init__(self, ibase):    Abstract   @classmethod  def getInstance(cls, ibase):    try:      cls.__instance    except AttributeError:      cls.__instance = new (cls, ibase)    return cls.__instance class StandardMathematicsSystem(MathematicsSystem):  def __init__(self, ibase):    if ibase.getBase() != new (IntegralNumber, 2):      raise NotImplementedError    self.base = ibase.getBase()   def calculateFactorial(self, target):    result = new (IntegralNumber, 1)    i = new (IntegralNumber, 2)    while i <= target:      result = result * i      i = i + new (IntegralNumber, 1)    return result print StandardMathematicsSystem.getInstance(new (InternalBase,new (IntegralNumber, 2))).calculateFactorial(new (IntegralNumber, 6))
[英文原文:The Evolution of a Python Programmer ]
 ','0');insert into `ecms_content_article_data` VALUES '894','896','

枚举

之前这样操作:

i = 0for item in iterable:  print i, item  i += 1

现在这样操作:

for i, item in enumerate(iterable):  print i, item

enumerate函数还可以接收第二个参数。就像下面这样:

>>> list(enumerate('abc')) [(0, 'a'
insert into `ecms_content_article_data` VALUES 1, 'b'
insert into `ecms_content_article_data` VALUES 2, 'c')]  >>> list(enumerate('abc', 1)) [(1, 'a'
insert into `ecms_content_article_data` VALUES 2, 'b'
insert into `ecms_content_article_data` VALUES 3, 'c')]

字典/集合 解析

你也许知道如何进行列表解析 但是可能不知道字典/集合解析。它们简单易用且高效。就像下面这个例子:

my_dict = {i: i * i for i in xrange(100)} my_set = {i * 15 for i in xrange(100)} # There is only a difference of ':' in both # 两者的区别在于字典推导中有冒号

强制浮点除法

如果除以一个整数 即使结果是一个浮点数 Python 2(校注 这里我添上了版本号)依旧会给一个整数。为了规避这个问题 需要这样做:

result = 1.0/2

但是现在有一种别的方法可以解决这个问题 甚至在之前我都没有意识到有这种方法存在。你可以进行如下操作:

from __future__ import division result = 1/2# print(result)# 0.5

瞧 现在你不需要在数据上附件".0" 来获得准确答案了。需要注意的是这个窍门只适用于Python 2。在Python 3 中就不需要进行import 操作了 因为它已经默认进行import了。

简单服务器

你是否想要快速方便的共享某个目录下的文件呢?你可以这么做:

# Python2python -m SimpleHTTPServer# Python 3python3 -m http.server

这样会为启动一个服务器。

对Python表达式求值

都知道eval函数 但是知道literal_eval函数么?也许很多人都不知道吧。可以用这种操作:

import ast my_list = ast.literal_eval(expr)

来代替以下这种操作:

expr = "[1, 2, 3]"my_list = eval(expr)

我相信对于大多数人来说这种形式是第一次看见 但是实际上这个在Python中已经存在很长时间了。

脚本分析

你可以很容易的通过运行以下代码进行脚本分析:

python -m cProfile my_script.py

对象自检

在Python 中你可以通过dir() 函数来检查对象。正如下面这个例子:

>>> foo = [1, 2, 3, 4]>>> dir(foo) ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', ... , 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

调试脚本

你可以很方便的通过pdb模块在你的脚本中设置断点。正如下面这个例子:

import pdbpdb.set_trace()

你可以在脚本的任何地方加入pdb.set_trace() 该函数会在那个位置设置一个断点。

if 结构简化

如果你需要检查几个数值你可以用以下方法:

if n in [1,4,5,6]:

来替代下面这个方式:

if n==1 or n==4 or n==5 or n==6:

字符串/数列 逆序

你可以用以下方法快速逆序排列数列:

>>> a = [1,2,3,4]>>> a[::-1][4, 3, 2, 1] # This creates a new reversed list. # If you want to reverse a list in place you can do: a.reverse()

这总方式也同样适用于字符串的逆序:

>>> foo = "yasoob">>> foo[::-1]'boosay'

优美地打印

你可以通过以下方式对字典和数列进行优美地打印:

from pprint import pprint pprint(my_dict)

这种方式对于字典打印更加高效。此外 如果你想要漂亮的将文件中的json文档打印出来 你可以用以下这种方式:

cat file.json | python -m json.tool

三元运算

三元运算是if-else 语句的快捷操作 也被称为条件运算。这里有几个例子可以供你参考 它们可以让你的代码更加紧凑 更加美观。

[on_true] if [expression] else [on_false]x, y = 50, 25small = x if x < y else y
 ','0' insert into `ecms_content_article_data` VALUES '948','950','

不久前 在互联网上出现了一篇有趣的文章 讲的是对于同一个问题 不同层次的程序员编出的 Python 代码显示出了不同的风格 代码都很简单 有趣。

编程新手

def factorial(x):  if x == 0:    return 1  else:    return x * factorial(x - 1)print factorial(6)

一年编程经验(学 Pascal 的)

def factorial(x):  result = 1  i = 2  while i <= x:    result = result * i    i = i + 1  return resultprint factorial(6)

一年编程经验(学 C 的)

def fact(x): #{  result = i = 1;  while (i <= x): #{    result *= i;    i += 1;  #}  return result;#}print(fact(6))

一年编程经验(读过 SICP)

@tailcalldef fact(x, acc=1):  if (x > 1): return (fact((x - 1
insert into `ecms_content_article_data` VALUES acc * x)))  else: return accprint(fact(6))

一年编程经验(Python)

def Factorial(x):  res = 1  for i in xrange(2, x + 1):    res *= i  return resprint Factorial(6)

懒惰的 Python 程序员

def fact(x):  return x > 1 and x * fact(x - 1) or 1print fact(6)

更懒的 Python 程序员

f = lambda x: x and x * f(x - 1) or 1print f(6)

Python 专家

import operator as opimport functional as ffact = lambda x: f.foldl(op.mul, 1, xrange(2, x + 1))print fact(6)

Python 黑客

import sys@tailcalldef fact(x, acc=1):  if x: return fact(x.__sub__(1), acc.__mul__(x))  return accsys.stdout.write(str(fact(6)) + '
')

专家级程序员

import c_mathfact = c_math.factprint fact(6)

大英帝国程序员

import c_mathsfact = c_maths.factprint fact(6)

Web 设计人员

def factorial(x):  #-------------------------------------------------  #--- 这段代码是从 Math Vault 那弄过来滴---  #--- 计算阶乘 (C)亚瑟·史密斯 1999年---  #-------------------------------------------------  result = str(1)  i = 1 #谢谢亚当  while i <= x:    #result = result * i #It's faster to use *=    #result = str(result * result + i)      #result = int(result *= i) #??????    result str(int(result) * i)    #result = int(str(result) * i)    i = i + 1  return resultprint factorial(6)

Unix 程序员

import osdef fact(x):  os.system('factorial ' + str(x))fact(6)

Windows 程序员

NULL = Nonedef CalculateAndPrintFactorialEx(dwNumber,                 hOutputDevice,                 lpLparam,                 lpWparam,                 lpsscSecurity,                 *dwReserved):  if lpsscSecurity != NULL:    return NULL #Not implemented  dwResult = dwCounter = 1  while dwCounter <= dwNumber:    dwResult *= dwCounter    dwCounter += 1  hOutputDevice.write(str(dwResult))  hOutputDevice.write('
')  return 1import sysCalculateAndPrintFactorialEx(6, sys.stdout, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)

企业级程序员

def new(cls, *args, **kwargs):  return cls(*args, **kwargs) class Number(object):  pass class IntegralNumber(int, Number):  def toInt(self):    return new (int, self) class InternalBase(object):  def __init__(self, base):    self.base = base.toInt()   def getBase(self):    return new (IntegralNumber, self.base) class MathematicsSystem(object):  def __init__(self, ibase):    Abstract   @classmethod  def getInstance(cls, ibase):    try:      cls.__instance    except AttributeError:      cls.__instance = new (cls, ibase)    return cls.__instance class StandardMathematicsSystem(MathematicsSystem):  def __init__(self, ibase):    if ibase.getBase() != new (IntegralNumber, 2):      raise NotImplementedError    self.base = ibase.getBase()   def calculateFactorial(self, target):    result = new (IntegralNumber, 1)    i = new (IntegralNumber, 2)    while i <= target:      result = result * i      i = i + new (IntegralNumber, 1)    return result print StandardMathematicsSystem.getInstance(new (InternalBase,new (IntegralNumber, 2))).calculateFactorial(new (IntegralNumber, 6))
[英文原文:The Evolution of a Python Programmer ]