首页 > 分享 > Python快速入门

Python快速入门

流程控制

python中通过缩进来代替括号,表示一个语句模块。

if语句 for语句 range函数 break,continue以及循环中的else语句 pass语句 定义函数

数据结构

链表:[]

链表是python中存放有序对象的容器,其中可以同时存放不同类型的数据。
常用方法:

append(x) #将元素插入链表末尾 extend(L) insert(i,x) remove(x) pop([i]) index(x) count(x) sort() reverse()123456789

函数化编程工具:filter、map、reduce
链表推导式
del语句

元组和序列:() Set

set()
与数学中集合的概念类似,有不同元素组成的集合。

字典:字典{}

存放无序key/value类型数据的容器,以关键字为索引,也被称为关联数组或者映射

列表推导式

通过列表推导式采用较为优雅的方式生成列表,避免了大量的代码冗余

>>>a[1,2,3,4,5] >>>mylist = [item*4 for item in a] >>>mtlist >>>[4,8,12,16,20]1234 深入理解循环 iteritems

在循环字典时,用方法iteritems()同时键值 1

knights = {’gallahad’: ’the pure’, ’robin’: ’the brave’} for k, v in knights.iteritems(): print k,v1234 enumerate

循环时,索引位置和循环值可以用enumerate同时得到。

for i, v in enumerate([’tic’, ’tac’, ’toe’]): print i, v12 zip()

>>> questions = [’name’, ’quest’, ’favorite color’] >>> answers = [’lancelot’, ’the holy grail’, ’blue’] >>> for q, a in zip(questions, answers): ... print ’What is your %s? It is %s.’ % (q, a) ... What is your name? It is lancelot. What is your quest? It is the holy grail. What is your favorite color? It is blue.123456789 sorted

>>> basket = [’apple’, ’orange’, ’apple’, ’pear’, ’orange’, ’banana’] >>> for f in sorted(set(basket)): ... print f ... apple banana orange pear123456789 reversed

>>> for i in reversed(xrange(1,10,2)): ... print i ... 9 7 5 3 1123456789 循环条件比较

in 、not in、is、is not、and 、or

>>> string1, string2, string3 = ’’, ’Trondheim’, ’Hammer Dance’ >>> non_null = string1 or string2 or string3 >>> non_null ’Trondheim’1234

序列之间的比较:比较按字典序进行,字符串按ASCII顺序

(1, 2, 3) < (1, 2, 4) [1, 2, 3] < [1, 2, 4] ’ABC’ < ’C’ < ’Pascal’ < ’Python’ (1, 2, 3, 4) < (1, 2, 4) (1, 2) < (1, 2, -1) (1, 2, 3) == (1.0, 2.0, 3.0) (1, 2, (’aa’, ’ab’)) < (1, 2, (’abc’, ’a’), 4)12345678910111213

输入输出

表达式语句print输出

通过str()、repr()将任意值转化为字符串

>>> s = ’Hello, world.’ >>> str(s) #转化为易于人读懂的形式 ’Hello, world.’ >>> repr(s) #转化为易于解释器理解的方式 "’Hello, world.’" >>> str(0.1) ’0.1’ >>> repr(0.1) ’0.10000000000000001’ >>> x = 10 * 3.25 >>> y = 200 * 200 >>> s = ’The value of x is ’ + repr(x) + ’, and y is ’ + repr(y) + ’...’ >>> print s The value of x is 32.5, and y is 40000... >>> # The repr() of a string adds string quotes and backslashes: ... hello = ’hello, worldn’ >>> hellos = repr(hello) >>> print hellos ’hello, worldn’ >>> # The argument to repr() may be any Python object: ... repr((x, y, (’spam’, ’eggs’))) "(32.5, 40000, (’spam’, ’eggs’))" >>> # reverse quotes are convenient in interactive sessions: ... ‘x, y, (’spam’, ’eggs’)‘ "(32.5, 40000, (’spam’, ’eggs’))"

12345678910111213141516171819202122232425

>>> for x in range(1, 11): ... print repr(x).rjust(2), repr(x*x).rjust(3), ... # Note trailing comma on previous line ... print repr(x*x*x).rjust(4) ... 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000 >>> for x in range(1,11): ... print ’%2d %3d %4d’ % (x, x*x, x*x*x) ... 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000

12345678910111213141516171819202122232425262728293031323334353637383940414243444546 读写文件

open函数返回一个文件
文件对象的read(size)方法读取文件
readline()方法从文件中读取一行
readlines()返回一个列表,其中包含所有数据行,如果传入参数会返回多个数据行
write(string)方法将string的内容写入文件
tell()方法返回一个整数,表示文件中指针的位置seek(offset,from_where)方法来改变文件指针

close关闭文件

pickle模块可以将任何Python模块封装为字符串
pickle.dum将对象封装
pickle.load将对象解封

>>> f=open(’/tmp/workfile’, ’w’) >>> print f <open file ’/tmp/workfile’, mode ’w’ at 80a0960>123

类和对象

类的定义语法

class ClassName: <statement-1> . . . <statement-N>123456

Tips: _doc_ 也是一个有效的属性,返回类的文档字符串
类的派生语法
可以通过_init_方法重写构造方法

class DerivedClassName(BaseClassName): <statement-1> . . . <statement-N> #多继承 class DerivedClassName(Base1, Base2, Base3): <statement-1> . . . <statement-N>12345678910111213

标准库概览

操作系统接口

提供与操作系统相关联的函数

>>> import os >>> os.system(’time 0:02’) 0 >>> os.getcwd() # Return the current working directory ’C:\Python24’ >>> os.chdir(’/server/accesslogs’)1234567

对于日常文件和目录处理,shutil模块是一个更易于使用的接口

>>> import shutil >>> shutil.copyfile(’data.db’, ’archive.db’) >>> shutil.move(’/build/executables’, ’installdir’)123 文件通配符

glob模块提供了函数,从目录通配符搜索中生成文件列表

>>> import glob >>> glob.glob(’*.py’) [’primes.py’, ’random.py’, ’quote.py’]123 命令行参数

命令行参数以链表的形式存于sys模块的argv变量

在命令中执行python demo.py one two three后

>>> import sys >>> print sys.argv [’demo.py’, ’one’, ’two’, ’three’]123 错误输出重定向和程序终止

>>> sys.stderr.write(’Warning, log file not found starting a new onen’) Warning, log file not found starting a new one12

大多数脚本的定向终止都使用sys.exit()

字符串正则匹配

>>> import re >>> re.findall(r’bf[a-z]*’, ’which foot or hand fell fastest’) [’foot’, ’fell’, ’fastest’] >>> re.sub(r’(b[a-z]+) 1’, r’1’, ’cat in the the hat’) ’cat in the hat’12345

>>> ’tea for too’.replace(’too’, ’two’) ’tea for two’12 数学

math模块对浮点运算提供了底层的C函数库的访问

>>> import math >>> math.cos(math.pi / 4.0) 0.70710678118654757 >>> math.log(1024, 2) 10.012345

random提供了生成随机数的工具

>>> import random >>> random.choice([’apple’, ’pear’, ’banana’]) ’apple’ >>> random.sample(xrange(100), 10) # sampling without replacement [30, 83, 16, 4, 8, 81, 41, 50, 18, 33] >>> random.random() # random float 0.17970987693706186 >>> random.randrange(6) # random integer chosen from range(6) 4123456789101112 互联网访问接口

urllib2模块从urls接受数据
smtplib模块用于发送电子邮件

>>> import urllib2 >>> for line in urllib2.urlopen(’http://tycho.usno.navy.mil/cgi-bin/timer.pl’): ... if ’EST’ in line or ’EDT’ in line: # look for Eastern Time ... print line <BR>Nov. 25, 09:43:32 PM EST >>> import smtplib >>> server = smtplib.SMTP(’localhost’) >>> server.sendmail(’soothsayer@example.org’, ’jcaesar@example.org’, """To: jcaesar@example.org From: soothsayer@example.org Beware the Ides of March. """) >>> server.quit123456789101112131415 日期和时间

# dates are easily constructed and formatted >>> from datetime import date >>> now = date.today() >>> now datetime.date(2003, 12, 2) >>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.") ’12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.’ # dates support calendar arithmetic >>> birthday = date(1964, 7, 31) >>> age = now - birthday >>> age.days 14368123456789101112 数据压缩

以下模块支持通用的数据打包和数据压缩格式
zlib 、gzip 、bz2 、zipfile 、 tarfile

>>> import zlib >>> s = ’witch which has which witches wrist watch’ >>> len(s) 41 >>> t = zlib.compress(s) >>> len(t) 37 >>> zlib.decompress(t) ’witch which has which witches wrist watch’ >>> zlib.crc32(s) 2268059791234567891011 格式化输出 多线程

import threading, zipfile class AsyncZip(threading.Thread): def __init__(self, infile, outfile): threading.Thread.__init__(self) self.infile = infile self.outfile = outfile def run(self): f = zipfile.ZipFile(self.outfile, ’w’, zipfile.ZIP_DEFLATED) f.write(self.infile) f.close() print ’Finished background zip of: ’, self.infile background = AsyncZip(’mydata.txt’, ’myarchive.zip’) background.start() print ’The main program continues to run in foreground.’ background.join() # Wait for the background task to finish print ’Main program waited until background was done.’

1234567891011121314151617 日志系统

通过logging记录信息并发送到文件或者sys.stderr

import logging logging.debug(’Debugging information’) logging.info(’Informational message’) logging.warning(’Warning:config file %s not found’, ’server.conf’) logging.error(’Error occurred’) logging.critical(’Critical error -- shutting down’)123456

WARNING:root:Warning:config file server.conf not found
ERROR:root:Error occurred
CRITICAL:root:Critical error – shutting down

相关知识

8天Python从入门到精通 第四章 Python循环语句 4.8 for循环的嵌套应用
《Python程序设计:人工智能案例实践》((美) 保罗·戴特尔(Paul Deitel))【简介
数据分析(Python)入门—鸢尾植物数据集处理
python 鸢尾花数据集下载
20行Python代码开发植物识别 app
学好Python=基础学科能力+业务知识+ IT技术
Python编写玫瑰花
如何快速使用Python神经网络识别手写字符?(文末福利)
Python文字花
探秘花语:基于Python的智能花卉图像识别系统

网址: Python快速入门 https://m.huajiangbk.com/newsview898877.html

所属分类:花卉
上一篇: 已知点G是△ABC的重心,过G作
下一篇: 19.数圈