本文内容主要从Learn Python The Hard Way、笨方法学python、RUNOOB.COM\Python3 教程整理汇总。
Python CommandsPython FormatKey WordsInput and Output Functions Basic IO Print on ScreenInput from keyboard File IO Data Type String Generate strings.String-Related Functions.Escape Sequences ListTupleDictionary Import FunctionDefine FunctionLogical FunctionConditional FunctionLoop FunctionClass Function Get Attributes From Class Iterator and Generator Iterator: iter() & next()Create IteratorExpection of StopIteration GeneratorPython脚本的首行应该添加:
# !/usr/bin/env python该命令用以引导脚本程序找到python的解释器(Interpreter)。 该命令仅适用于linux/unix环境,因为它们根据文件的首部内容决定文件的执行方式。 而windows环境根据后缀名决定文件的执行方式。
Python脚本的首部还应该添加:
# coding:utf-8该命令表示该脚本使用utf-8编码格式,如此该脚本内容使用的中文才能被正常显示。
str.split()
功能:根据delimiter将字符串分割。
函数形式:
str.split(delimiter=None, num=-1)参数解释:
参数解释delimiter分隔符可以是space, \n, \t等。分隔符不存在时,分割所有类型的分隔符。num默认值为1,此时分割所有分隔符。如果给定数目少于分隔符最大数目,则前num个元素被分割。返回值:返回分割后的字符串列表。
str.isalnum()
功能:检查是否所有元素都是数字。
str.join(iterable)
功能:返回一个将iterable中所有元素连接并以str为连接符的字符串。
功能:包含一组有序元素,元素由index索引。其中元素类型可以是数字、字符串、列表、字典、函数。
# list construction hairs = ['brown', 'blond', 'red'] eys = ['brown', 'blue', 'green'] weights = [1, 2, 3, 4] # list functions ## remove and return item with given index. If index is not given, the last item is removed. itemPop = list.pop([index])元组与列表类似,不同之处在于元组的元素不能修改。
# tuple construction. tuple1 = ('Google', 'Runnob', 1997, 2000) tuple2 = 'a', 'b', 'c', 'd' emptyTuple = () # delete tuple. del tuple1 # add tuple. tuple3 = tuple1 + tuple2 # initialize values for a tuple of variables. a, b, c = 1, 2, 3功能:包含一组键值和对应元素,元素由键值key索引。其中元素类型可以是数字、字符串、列表、字典、函数。
# dict construction. stuff = {'name': 'Zed', 'age': 36, 'height': 6 * 12 + 2} # check whether keys exist in dict. if '0' not in next or '1' in next: # delete element in dictionary. del stuff['name'] # list all items in dictionary. Items include key and value. Can be used for iterable accessing. dictEg.items() # create and return a dict with keys in listKey and values equal to initValues. dictEg = dict.fromkeys([listKey], initValues) # return an iterable key and can be changed to list using list() keyIterable = dictEg.keys() keyList = list(dictEg.keys())NOTE: 当字典的键值为列表或字典时,为了获取/赋值键值中字典/列表的值,有两种方法可以实现:
方法一:逐层引用,先赋值/获取最高层的键值,再赋值/获取下一层的值: # assign values. dic1 = {'test': {}, 'anchor': {}} dic11 = {'qp1': 32, 'qp2': 37} dic12 = {'qp1': 22, 'qp2': 27} dic1['test'] = dic11 dic1['anchor'] = dic12 # obtain values. val111 = dic1.get('test')['qp1'] # get() can be replaced by setdefault(). val122 = dic1.get('anchor')['qp2'] # get() can be replaced by setdefault(). 方法二:多重索引引用,类似C++中二维数组的使用: # assign values. dic1 = {'test': {}, 'anchor': {}} dic1['test']['qp1'] = 32 dic1['test']['qp2'] = 37 dic1['anchor']['qp1'] = 22 dic1['anchor']['qp2'] = 27 # obtain values. val111 = dic1['test']['qp1'] val122 = dic1['anchor']['qp2']值得注意的是,方法二的赋值和获取在vscode中会被pylint标记为error,但是并不影响执行结果。目前还不太清楚是否方法二会产生什么问题,有待学习。
功能:迭代器从集合的第一个元素开始访问,知道所有的元素被访问完结束。
特点:
迭代器只能前进不能后退。字符串、列表和元祖对象(即有序对象)都可以用于创建迭代器。创建迭代器类需要在类中实现两个方法__iter__()和__next__()。
# create a iterator which start from 1 and increase with step 1. class MyNumbers: def __iter__(self): self.a = 1 return self def __next__(self): x = self.a self.a += 1 return x # run MyNumbers iterator. myClass = MyNumbers() myIter = iter(myClass) print(next(myIter)) print(next(myIter))StopIteration异常用于标识迭代的完成,防止出现无限循环的情况,可以在__next__()方法中设置在完成指定循环次数后触发异常来结束迭代。
class MyNumbers: def __iter__(self): self.a = 1 return self def __next__(self): if self.a <= 20: x = self.a self.a += 1 return x else: raise StopIteration定义:使用了yield的函数被称为生成器Generator。
特性:
生成器是一个返回迭代器的函数,只能用于迭代操作。调用生成器运行时,每次遇到yield时函数会暂停并保存当前所有的运行信息,返回yield的值,并在下一次执行next()方法时从当前位置继续运行。生成器的返回值为迭代器对象。 import sys def fibonacci(n): # this is a generator. a, b, counter = 0, 1, 0 while True: if counter > n: return StopIteration yield a a, b = b, a + b counter += 1 f = fibonacci(10) # f is an iterator. while True: try: print(next(f), end=' ') except StopIteration: sys.exit()