Python语法速览与实战清单

本文是对于 现代 Python 开发:语法基础与工程实践的总结,更多 Python 相关资料参考 Python 学习与实践资料索引;本文参考了 Python Crash Course - Cheat Sheets,pysheeet 等。本文仅包含笔者在日常工作中经常使用的,并且认为较为关键的知识点与语法,如果想要进一步学习 Python 相关内容或者对于机器学习与数据挖掘方向感兴趣,可以参考程序猿的数据科学与机器学习实战手册。

站在用户的角度思考问题,与客户深入沟通,找到浦北网站设计与浦北网站推广的解决方案,凭借多年的经验,让设计与互联网技术结合,创造个性化、用户体验好的作品,建站类型包括:网站设计、成都网站建设、企业官网、英文网站、手机端网站、网站推广、国际域名空间、虚拟空间、企业邮箱。业务覆盖浦北地区。

基础语法

Python 是一门高阶、动态类型的多范式编程语言;定义 Python 文件的时候我们往往会先声明文件编码方式:

 
 
 
  1. # 指定脚本调用方式
  2. #!/usr/bin/env python
  3. # 配置 utf-8 编码
  4. # -*- coding: utf-8 -*-
  5. # 配置其他编码
  6. # -*- coding:  -*-
  7. # Vim 中还可以使用如下方式
  8. # vim:fileencoding=

人生苦短,请用 Python,大量功能强大的语法糖的同时让很多时候 Python 代码看上去有点像伪代码。譬如我们用 Python 实现的简易的快排相较于 Java 会显得很短小精悍:

 
 
 
  1. def quicksort(arr):
  2.     if len(arr) <= 1:
  3.         return arr
  4.     pivot = arr[len(arr) / 2]
  5.     left = [x for x in arr if x < pivot]
  6.     middle = [x for x in arr if x == pivot]
  7.     right = [x for x in arr if x > pivot]
  8.     return quicksort(left) + middle + quicksort(right)
  9.     
  10. print quicksort([3,6,8,10,1,2,1])
  11. # Prints "[1, 1, 2, 3, 6, 8, 10]"

控制台交互

可以根据 __name__ 关键字来判断是否是直接使用 python 命令执行某个脚本,还是外部引用;Google 开源的 fire 也是不错的快速将某个类封装为命令行工具的框架:

 
 
 
  1. import fire
  2. class Calculator(object):
  3.   """A simple calculator class."""
  4.   def double(self, number):
  5.     return 2 * number
  6. if __name__ == '__main__':
  7.   fire.Fire(Calculator)
  8. # python calculator.py double 10  # 20
  9. # python calculator.py double --number=15  # 30

Python 2 中 print 是表达式,而 Python 3 中 print 是函数;如果希望在 Python 2 中将 print 以函数方式使用,则需要自定义引入:

 
 
 
  1. from __future__ import print_function

我们也可以使用 pprint 来美化控制台输出内容:

 
 
 
  1. import pprint
  2. stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
  3. pprint.pprint(stuff)
  4. # 自定义参数
  5. pp = pprint.PrettyPrinter(depth=6)
  6. tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead',('parrot', ('fresh fruit',))))))))
  7. pp.pprint(tup)

模块

Python 中的模块(Module)即是 Python 源码文件,其可以导出类、函数与全局变量;当我们从某个模块导入变量时,函数名往往就是命名空间(Namespace)。而 Python 中的包(Package)则是模块的文件夹,往往由 __init__.py 指明某个文件夹为包:

 
 
 
  1. # 文件目录
  2. someDir/
  3.     main.py
  4.     siblingModule.py
  5. # siblingModule.py
  6. def siblingModuleFun():
  7.     print('Hello from siblingModuleFun')
  8.     
  9. def siblingModuleFunTwo():
  10.     print('Hello from siblingModuleFunTwo')
  11. import siblingModule
  12. import siblingModule as sibMod
  13. sibMod.siblingModuleFun()
  14. from siblingModule import siblingModuleFun
  15. siblingModuleFun()
  16. try:
  17.     # Import 'someModuleA' that is only available in Windows
  18.     import someModuleA
  19. except ImportError:
  20.     try:
  21.         # Import 'someModuleB' that is only available in Linux
  22.         import someModuleB
  23.     except ImportError:

Package 可以为某个目录下所有的文件设置统一入口:

 
 
 
  1. someDir/
  2.     main.py
  3.     subModules/
  4.         __init__.py
  5.         subA.py
  6.         subSubModules/
  7.             __init__.py
  8.             subSubA.py
  9. # subA.py
  10. def subAFun():
  11.     print('Hello from subAFun')
  12.     
  13. def subAFunTwo():
  14.     print('Hello from subAFunTwo')
  15. # subSubA.py
  16. def subSubAFun():
  17.     print('Hello from subSubAFun')
  18.     
  19. def subSubAFunTwo():
  20.     print('Hello from subSubAFunTwo')
  21. # __init__.py from subDir
  22. # Adds 'subAFun()' and 'subAFunTwo()' to the 'subDir' namespace 
  23. from .subA import *
  24. # The following two import statement do the same thing, they add 'subSubAFun()' and 'subSubAFunTwo()' to the 'subDir' namespace. The first one assumes '__init__.py' is empty in 'subSubDir', and the second one, assumes '__init__.py' in 'subSubDir' contains 'from .subSubA import *'.
  25. # Assumes '__init__.py' is empty in 'subSubDir'
  26. # Adds 'subSubAFun()' and 'subSubAFunTwo()' to the 'subDir' namespace
  27. from .subSubDir.subSubA import *
  28. # Assumes '__init__.py' in 'subSubDir' has 'from .subSubA import *'
  29. # Adds 'subSubAFun()' and 'subSubAFunTwo()' to the 'subDir' namespace
  30. from .subSubDir import *
  31. # __init__.py from subSubDir
  32. # Adds 'subSubAFun()' and 'subSubAFunTwo()' to the 'subSubDir' namespace
  33. from .subSubA import *
  34. # main.py
  35. import subDir
  36. subDir.subAFun() # Hello from subAFun
  37. subDir.subAFunTwo() # Hello from subAFunTwo
  38. subDir.subSubAFun() # Hello from subSubAFun
  39. subDir.subSubAFunTwo() # Hello from subSubAFunTwo

表达式与控制流

条件选择

Python 中使用 if、elif、else 来进行基础的条件选择操作:

 
 
 
  1. if x < 0:
  2.      x = 0
  3.      print('Negative changed to zero')
  4.  elif x == 0:
  5.      print('Zero')
  6.  else:
  7.      print('More')

Python 同样支持 ternary conditional operator:

 
 
 
  1. a if condition else b

也可以使用 Tuple 来实现类似的效果:

 
 
 
  1. # test 需要返回 True 或者 False
  2. (falseValue, trueValue)[test]
  3. # 更安全的做法是进行强制判断
  4. (falseValue, trueValue)[test == True]
  5. # 或者使用 bool 类型转换函数
  6. (falseValue, trueValue)[bool()]

循环遍历

for-in 可以用来遍历数组与字典:

 
 
 
  1. words = ['cat', 'window', 'defenestrate']
  2. for w in words:
  3.     print(w, len(w))
  4. # 使用数组访问操作符,能够迅速地生成数组的副本
  5. for w in words[:]:
  6.     if len(w) > 6:
  7.         words.insert(0, w)
  8. # words -> ['defenestrate', 'cat', 'window', 'defenestrate']

如果我们希望使用数字序列进行遍历,可以使用 Python 内置的 range 函数:

 
 
 
  1. a = ['Mary', 'had', 'a', 'little', 'lamb']
  2. for i in range(len(a)):
  3.     print(i, a[i])

基本数据类型

可以使用内建函数进行强制类型转换(Casting):

 
 
 
  1. int(str)
  2. float(str)
  3. str(int)
  4. str(float)

Number: 数值类型

 
 
 
  1. x = 3
  2. print type(x) # Prints ""
  3. print x       # Prints "3"
  4. print x + 1   # Addition; prints "4"
  5. print x - 1   # Subtraction; prints "2"
  6. print x * 2   # Multiplication; prints "6"
  7. print x ** 2  # Exponentiation; prints "9"
  8. x += 1
  9. print x  # Prints "4"
  10. x *= 2
  11. print x  # Prints "8"
  12. y = 2.5
  13. print type(y) # Prints ""
  14. print y, y + 1, y * 2, y ** 2 # Prints "2.5 3.5 5.0 6.25"

布尔类型

Python 提供了常见的逻辑操作符,不过需要注意的是 Python 中并没有使用 &&、|| 等,而是直接使用了英文单词。

 
 
 
  1. t = True
  2. f = False
  3. print type(t) # Prints ""
  4. print t and f # Logical AND; prints "False"
  5. print t or f  # Logical OR; prints "True"
  6. print not t   # Logical NOT; prints "False"
  7. print t != f  # Logical XOR; prints "True" 

String: 字符串

Python 2 中支持 Ascii 码的 str() 类型,独立的 unicode() 类型,没有 byte 类型;而 Python 3 中默认的字符串为 utf-8 类型,并且包含了 byte 与 bytearray 两个字节类型:

 
 
 
  1. type("Guido") # string type is str in python2
  2. # 使用 __future__ 中提供的模块来降级使用 Unicode
  3. from __future__ import unicode_literals
  4. type("Guido") # string type become unicode

Python 字符串支持分片、模板字符串等常见操作:

 
 
 
  1. var1 = 'Hello World!'
  2. var2 = "Python Programming"
  3. print "var1[0]: ", var1[0]
  4. print "var2[1:5]: ", var2[1:5]
  5. # var1[0]:  H
  6. # var2[1:5]:  ytho
  7. print "My name is %s and weight is %d kg!" % ('Zara', 21)
  8. # My name is Zara and weight is 21 kg!
  9. str[0:4]
  10. len(str)
  11. string.replace("-", " ")
  12. ",".join(list)
  13. "hi {0}".format('j')
  14. str.find(",")
  15. str.index(",")   # same, but raises IndexError
  16. str.count(",")
  17. str.split(",")
  18. str.lower()
  19. str.upper()
  20. str.title()
  21. str.lstrip()
  22. str.rstrip()
  23. str.strip()
  24. str.islower()
  25. # 移除所有的特殊字符
  26. re.sub('[^A-Za-z0-9]+', '', mystring) 

如果需要判断是否包含某个子字符串,或者搜索某个字符串的下标:

 
 
 
  1. # in 操作符可以判断字符串
  2. if "blah" not in somestring: 
  3.     continue
  4. # find 可以搜索下标
  5. s = "This be a string"
  6. if s.find("is") == -1:
  7.     print "No 'is' here!"
  8. else:
  9.     print "Found 'is' in the string."

Regex: 正则表达式

 
 
 
  1. import re
  2. # 判断是否匹配
  3. re.match(r'^[aeiou]', str)
  4. # 以第二个参数指定的字符替换原字符串中内容
  5. re.sub(r'^[aeiou]', '?', str)
  6. re.sub(r'(xyz)', r'\1', str)
  7. # 编译生成独立的正则表达式对象
  8. expr = re.compile(r'^...$')
  9. expr.match(...)
  10. expr.sub(...)

下面列举了常见的表达式使用场景:

 
 
 
  1. # 检测是否为 HTML 标签
  2. re.search('<[^/>][^>]*>', '')
  3. # 常见的用户名密码
  4. re.match('^[a-zA-Z0-9-_]{3,16}$', 'Foo') is not None
  5. re.match('^\w|[-_]{3,16}$', 'Foo') is not None
  6. # Email
  7. re.match('^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$', 'hello.world@cdxwcx.com')
  8. # Url
  9. exp = re.compile(r'''^(https?:\/\/)? # match http or https
  10.                 ([\da-z\.-]+)            # match domain
  11.                 \.([a-z\.]{2,6})         # match domain
  12.                 ([\/\w \.-]*)\/?$        # match api or file
  13.                 ''', re.X)
  14. exp.match('www.google.com')
  15. # IP 地址
  16. exp = re.compile(r'''^(?:(?:25[0-5]
  17.                      |2[0-4][0-9]
  18.                      |[1]?[0-9][0-9]?)\.){3}
  19.                      (?:25[0-5]
  20.                      |2[0-4][0-9]
  21.                      |[1]?[0-9][0-9]?)$''', re.X)
  22. exp.match('192.168.1.1')

集合类型

List: 列表

Operation: 创建增删

 
 
 
  1. l = []
  2. l = list()
  3. # 使用字符串的 split 方法,可以将字符串转化为列表
  4. str.split(".")
  5. # 如果需要将数组拼装为字符串,则可以使用 join 
  6. list1 = ['1', '2', '3']
  7. str1 = ''.join(list1)
  8. # 如果是数值数组,则需要先进行转换
  9. list1 = [1, 2, 3]
  10. str1 = ''.join(str(e) for e in list1)

可以使用 append 与 extend 向数组中插入元素或者进行数组连接

 
 
 
  1. x = [1, 2, 3]
  2. x.append([4, 5]) # [1, 2, 3, [4, 5]]
  3. x.extend([4, 5]) # [1, 2, 3, 4, 5],注意 extend 返回值为 None

可以使用 pop、slices、del、remove 等移除列表中元素:

 
 
 
  1. myList = [10,20,30,40,50]
  2. # 弹出第二个元素
  3. myList.pop(1) # 20
  4. # myList: myList.pop(1)
  5. # 如果不加任何参数,则默认弹出***一个元素
  6. myList.pop()
  7. # 使用 slices 来删除某个元素
  8. a = [  1, 2, 3, 4, 5, 6 ]
  9. index = 3 # Only Positive index
  10. a = a[:index] + a[index+1 :]
  11. # 根据下标删除元素
  12. myList = [10,20,30,40,50]
  13. rmovIndxNo = 3
  14. del myList[rmovIndxNo] # myList: [10, 20, 30, 50]
  15. # 使用 remove 方法,直接根据元素删除
  16. letters = ["a", "b", "c", "d", "e"]
  17. numbers.remove(numbers[1])
  18. print(*letters) # used a * to make it unpack you don't have to

Iteration: 索引遍历

你可以使用基本的 for 循环来遍历数组中的元素,就像下面介个样纸:

 
 
 
  1. animals = ['cat', 'dog', 'monkey']
  2. for animal in animals:
  3.     print animal
  4. # Prints "cat", "dog", "monkey", each on its own line.

如果你在循环的同时也希望能够获取到当前元素下标,可以使用 enumerate 函数:

 
 
 
  1. animals = ['cat', 'dog', 'monkey']
  2. for idx, animal in enumerate(animals):
  3.     print '#%d: %s' % (idx + 1, animal)
  4. # Prints "#1: cat", "#2: dog", "#3: monkey", each on its own line

Python 也支持切片(Slices):

 
 
 
  1. nums = range(5)    # range is a built-in function that creates a list of integers
  2. print nums         # Prints "[0, 1, 2, 3, 4]"
  3. print nums[2:4]    # Get a slice from index 2 to 4 (exclusive); prints "[2, 3]"
  4. print nums[2:]     # Get a slice from index 2 to the end; prints "[2, 3, 4]"
  5. print nums[:2]     # Get a slice from the start to index 2 (exclusive); prints "[0, 1]"
  6. print nums[:]      # Get a slice of the whole list; prints ["0, 1, 2, 3, 4]"
  7. print nums[:-1]    # Slice indices can be negative; prints ["0, 1, 2, 3]"
  8. nums[2:4] = [8, 9] # Assign a new sublist to a slice
  9. print nums         # Prints "[0, 1, 8, 9, 4]"

Comprehensions: 变换

Python 中同样可以使用 map、reduce、filter,map 用于变换数组:

 
 
 
  1. # 使用 map 对数组中的每个元素计算平方
  2. items = [1, 2, 3, 4, 5]
  3. squared = list(map(lambda x: x**2, items))
  4. # map 支持函数以数组方式连接使用
  5. def multiply(x):
  6.     return (x*x)
  7. def add(x):
  8.     return (x+x)
  9. funcs = [multiply, add]
  10. for i in range(5):
  11.     value = list(map(lambda x: x(i), funcs))
  12.     print(value)

reduce 用于进行归纳计算:

 
 
 
  1. # reduce 将数组中的值进行归纳
  2. from functools import reduce
  3. product = reduce((lambda x, y: x * y), [1, 2, 3, 4])
  4. # Output: 24

filter 则可以对数组进行过滤:

 
 
 
  1. number_list = range(-5, 5)
  2. less_than_zero = list(filter(lambda x: x < 0, number_list))
  3. print(less_than_zero)
  4. # Output: [-5, -4, -3, -2, -1]

字典类型

创建增删

 
 
 
  1. d = {'cat': 'cute', 'dog': 'furry'}  # 创建新的字典
  2. print d['cat']       # 字典不支持点(Dot)运算符取值

如果需要合并两个或者多个字典类型:

 
 
 
  1. # python 3.5
  2. z = {**x, **y}
  3. # python 2.7
  4. def merge_dicts(*dict_args):
  5.     """
  6.     Given any number of dicts, shallow copy and merge into a new dict,
  7.     precedence goes to key value pairs in latter dicts.
  8.     """
  9.     result = {}
  10.     for dictionary in dict_args:
  11.         result.update(dictionary)
  12.     return result

索引遍历

可以根据键来直接进行元素访问:

 
 
 
  1. # Python 中对于访问不存在的键会抛出 KeyError 异常,需要先行判断或者使用 get
  2. print 'cat' in d     # Check if a dictionary has a given key; prints "True"
  3. # 如果直接使用 [] 来取值,需要先确定键的存在,否则会抛出异常
  4. print d['monkey']  # KeyError: 'monkey' not a key of d
  5. # 使用 get 函数则可以设置默认值
  6. print d.get('monkey', 'N/A')  # Get an element with a default; prints "N/A"
  7. print d.get('fish', 'N/A')    # Get an element with a default; prints "wet"
  8. d.keys() # 使用 keys 方法可以获取所有的键

可以使用 for-in 来遍历数组:

 
 
 
  1. # 遍历键
  2. for key in d:
  3. # 比前一种方式慢
  4. for k in dict.keys(): ...
  5. # 直接遍历值
  6. for value in dict.itervalues(): ...
  7. # Python 2.x 中遍历键值
  8. for key, value in d.iteritems():
  9. # Python 3.x 中遍历键值
  10. for key, value in d.items():

其他序列类型

集合

 
 
 
  1. # Same as {"a", "b","c"}
  2. normal_set = set(["a", "b","c"])
  3.  
  4. # Adding an element to normal set is fine
  5. normal_set.add("d")
  6.  
  7. print("Normal Set")
  8. print(normal_set)
  9.  
  10. # A frozen set
  11. frozen_set = frozenset(["e", "f", "g"])
  12.  
  13. print("Frozen Set")
  14. print(frozen_set)
  15.  
  16. # Uncommenting below line would cause error as
  17. # we are trying to add element to a frozen set
  18. # frozen_set.add("h")

函数

函数定义

Python 中的函数使用 def 关键字进行定义,譬如:

 
 
 
  1. def sign(x):
  2.     if x > 0:
  3.         return 'positive'
  4.     elif x < 0:
  5.         return 'negative'
  6.     else:
  7.         return 'zero'
  8. for x in [-1, 0, 1]:
  9.     print sign(x)
  10. # Prints "negative", "zero", "positive"

Python 支持运行时创建动态函数,也即是所谓的 lambda 函数:

 
 
 
  1. def f(x): return x**2
  2. # 等价于
  3. g = lambda x: x**2

参数

Option Arguments: 不定参数

 
 
 
  1. def example(a, b=None, *args, **kwargs):
  2.   print a, b
  3.   print args
  4.   print kwargs
  5. example(1, "var", 2, 3, word="hello")
  6. # 1 var
  7. # (2, 3)
  8. # {'word': 'hello'}
  9. a_tuple = (1, 2, 3, 4, 5)
  10. a_dict = {"1":1, "2":2, "3":3}
  11. example(1, "var", *a_tuple, **a_dict)
  12. # 1 var
  13. # (1, 2, 3, 4, 5)
  14. # {'1': 1, '2': 2, '3': 3}

生成器

 
 
 
  1. def simple_generator_function():
  2.     yield 1
  3.     yield 2
  4.     yield 3
  5. for value in simple_generator_function():
  6.     print(value)
  7. # 输出结果
  8. # 1
  9. # 2
  10. # 3
  11. our_generator = simple_generator_function()
  12. next(our_generator)
  13. # 1
  14. next(our_generator)
  15. # 2
  16. next(our_generator)
  17. #3
  18. # 生成器典型的使用场景譬如***数组的迭代
  19. def get_primes(number):
  20.     while True:
  21.         if is_prime(number):
  22.             yield number
  23.         number += 1

装饰器

装饰器是非常有用的设计模式:

 
 
 
  1. # 简单装饰器
  2. from functools import wraps
  3. def decorator(func):
  4.     @wraps(func)
  5.     def wrapper(*args, **kwargs):
  6.         print('wrap function')
  7.         return func(*args, **kwargs)
  8.     return wrapper
  9. @decorator
  10. def example(*a, **kw):
  11.     pass
  12. example.__name__  # attr of function preserve
  13. # 'example'
  14. # Decorator 
  15. # 带输入值的装饰器
  16. from functools import wraps
  17. def decorator_with_argument(val):
  18.   def decorator(func):
  19.     @wraps(func)
  20.     def wrapper(*args, **kwargs):
  21.       print "Val is {0}".format(val)
  22.       return func(*args, **kwargs)
  23.     return wrapper
  24.   return decorator
  25. @decorator_with_argument(10)
  26. def example():
  27.   print "This is example function."
  28. example()
  29. # Val is 10
  30. # This is example function.
  31. # 等价于
  32. def example():
  33.   print "This is example function."
  34. example = decorator_with_argument(10)(example)
  35. example()
  36. # Val is 10
  37. # This is example function.

类与对象

类定义

Python 中对于类的定义也很直接:

 
 
 
  1. class Greeter(object):
  2.     
  3.     # Constructor
  4.     def __init__(self, name):
  5.         self.name = name  # Create an instance variable
  6.         
  7.     # Instance method
  8.     def greet(self, loud=False):
  9.         if loud:
  10.             print 'HELLO, %s!' % self.name.upper()
  11.         else:
  12.             print 'Hello, %s' % self.name
  13.         
  14. g = Greeter('Fred')  # Construct an instance of the Greeter class
  15. g.greet()            # Call an instance method; prints "Hello, Fred"
  16. g.greet(loud=True)   # Call an instance method; prints "HELLO, FRED!"
  17. # isinstance 方法用于判断某个对象是否源自某个类
  18. ex = 10
  19. isinstance(ex,int)

Managed Attributes: 受控属性

 
 
 
  1. # property、setter、deleter 可以用于复写点方法
  2. class Example(object):
  3.     def __init__(self, value):
  4.        self._val = value
  5.     @property
  6.     def val(self):
  7.         return self._val
  8.     @val.setter
  9.     def val(self, value):
  10.         if not isintance(value, int):
  11.             raise TypeError("Expected int")
  12.         self._val = value
  13.     @val.deleter
  14.     def val(self):
  15.         del self._val
  16.     @property
  17.     def square3(self):
  18.         return 2**3
  19. ex = Example(123)
  20. ex.val = "str"
  21. # Traceback (most recent call last):
  22. #   File "", line 1, in
  23. #   File "test.py", line 12, in val
  24. #     raise TypeError("Expected int")
  25. # TypeError: Expected int

类方法与静态方法

 
 
 
  1. class example(object):
  2.   @classmethod
  3.   def clsmethod(cls):
  4.     print "I am classmethod"
  5.   @staticmethod
  6.   def stmethod():
  7. 新闻名称:Python语法速览与实战清单
    网站网址:http://www.csdahua.cn/qtweb/news20/405170.html

    网站建设、网络推广公司-快上网,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

    广告

    声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 快上网