Python学习笔记
来源:互联网 发布:铁路局通信段 知乎 编辑:程序博客网 时间:2024/06/02 13:18
因在面试的时候会一门脚本语言是有很大优势的,所以今天华为机试回来愉快的决定将Python纳入复习计划之中,先学习重要的语法,然后和波波讨论写个简单的服务器,如果来得及的话,就实现个搜索引擎,最后,每次刷题时,尝试用Python,我的windows编译器版本是2.7.7。参考书是《Python基础教程(第2版)》Hetland,
大致将基础看完,然后结合例子练一练。
2014年8月15日23:24:04:看了前5章,是很基础的,下面再看一遍,尝试用Python刷题。
加油,
更新:2014年11月29日
最近看了http://www.liaoxuefeng.com/的博客,里面的例子很好,很适合外行快速入门,不需要深入了解他,只需要知道他是什么就可以了。
看到 装饰器 了(这个总体还是比较有用的,自己多看看,下次接着看吧)
当Python解释器读取源代码时,为了让他按UTF-8编码读取,我们通常在文件开头写上这两行:
#!/usr/bin/env python# -*- coding: utf-8 -*-
Web开发 看了一点,没有看懂。
常见面试题:
1、请教一下列表与元组的区别是什么.分别在什么情况下使用?字典呢?
2、Python是如何进行内存管理的?
答:http://blog.chinaunix.net/uid-26602509-id-3506965.html
3、解释一下python的 and-or 语法
答:http://www.cnblogs.com/BeginMan/p/3197123.html
4、Python里面如何拷贝一个对象?
Python中的对象之间赋值时是按引用传递的,如果需要拷贝对象,需要使用标准库中的copy模块。
1) copy.copy 浅拷贝 只拷贝父对象,不会拷贝对象的内部的子对象。
2) copy.deepcopy 深拷贝 拷贝对象及其子对象
5、如何在一个function里面设置一个全局的变量?
答:解决方法是在function的开始插入一个global声明
6、pass语句什么也不做,一般作为占位符或者创建占位程序,pass语句不会执行任何操作
7、参数是如何传递的?
答:在Python中一切都是对象,任何变量都是对象的引用,你不能改变引用,但是你可以改变可变对象,数字,string, tuple是不可变得,list和dict是可变的。
8、什么是列表和字典推导(list and dict comprehensions)?你能给个例子吗?
答:列表字典推导是一种语法糖,用来简化列表和字典的生成。
# simple iterationa = []for x in range(10): a.append(x*2)# a == [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]# list comprehensiona = [x*2 for x in range(10)]# dict comprehensiona = {x: x*2 for x in range(10)}# a == {0: 0, 1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18# set comprehensiona = {x**2 for x in range(10) if x % 2 == 0}# a == set([0, 16, 4, 64, 36])
9、什么是PEP8?
答:PEP8定义的是Python代码规范,告诉你如何书写可读性强、更好维护的代码。
10、你用过虚拟环境吗?
答:用过,virtualenv用来孤立你的开发和运行环境,特别是当需要同时开发多个项目,基于不同的 Python 版本以及运行库的时候。
11、如何计算list中元素之和?之积?
# 计算列表内所有元素的和, 包括基本loop方式,sum函数方式,以及使用reduce函数# the basic ways = 0for x in range(10): s += x# the right ways = sum(range(10))# the other wayfrom operator import adds = reduce(add, range(10))# 计算列表内所有元素的乘积# the basic ways = 1for x in range(1, 10): s = s * x# the other wayfrom operator import mulreduce(mul, range(1, 10)) #ref: http://www.cnblogs.com/dwnblogs/archive/2012/10/26/2741169.html
12、list和tuple的区别,举例子?
答:list可改变,tuple不可改变,可用作hash值,比如作为dict的key。
13、range和xrange的区别?
答:1)range返回list对象,而xrange返回xrange对象(大小固定),列表对象已经在内存中存在了,而xrange
对象永远占 用同样的内存大小,无论需要生成的range
有多大。2)xrange对象不能使用列表对象的切片函数。
14、Python2.x和3.x的区别?
15、什么是装饰器(decorator),用法?
答:装饰器允许你在函数或类中插入和修改代码,也就是在执行原代码之前或之后执行程序;
常见用法:记录某函数调用,权限检查,
内存缓存:
def memoize(f): memo = {} # 将结果缓存在memo字典对象中,key是参数,value是结果。 def helper(x): if x not in memo: memo[x] = f(x) return memo[x] return helper # 修饰fib函数,任何fib函数的调用,将首先察看是否已经有缓存的结果 @memoize def fib(n): if n == 0: return 0 elif n == 1: return 1 else: return fib(n-1) + fib(n-2) print(fib(40)) # 102334155参数检查
def argument_test_natural_number(f): def helper(x): if type(x) == int and x > 0: return f(x) else: raise Exception("Argument is not an integer") return helper @argument_test_natural_number def faculty(n): if n == 1: return 1 else: return n * faculty(n-1) for i in range(1,10): print(i, faculty(i)) # 1 1 # 2 2 # 3 6 # 4 24 # 5 120 # 6 720 # 7 5040 # 8 40320 # 9 362880 faculty(-1) # 使用非法的参数调用faculty函数,这将raise一个exception # Exception: Argument is not an integer
16、Package/Module的定义以及模块加载原则?
答:模块就是可重用的代码段,要告诉解释器到哪寻找模块,可增加测试代码,用__name__判断是否在“主程序”中(__main__)。
为了更好的组织模块,可将它们分组为包(package)。必须包含__init__py的文件。
17,、什么是迭代器(iterator)?什么是Python生成器(generator),如何使用?
答:
1)迭代器对象要求支持迭代器协议,所谓支持迭代器协议就是对象包含__iter__()和next()方法。其中__iter__()方法返回迭代器对象自己;next()方法返回下一个前进到下一个结果,在结尾时引发StopIteration异常。
2)生成器使python可以很容易的支持迭代协议。生成器通过生成器函数产生,生成器函数可以通过常规的def语句来定义,但是不用return返回,而是用yeild一次返回一个结果,在每个结果之间挂起和继续它们的状态,来自动实现迭代协议。
参考网页:
http://ilian.i-n-i.org/python-interview-question-and-answers/
http://xiaocong.github.io/blog/2013/06/16/python-interview-question-and-answer/
下面把 ch2 ch3 ch4这三章好好看看。
第二章:列表和元祖
Python包含6种内建的序列:列表,元祖,字符串,Unicode字符串,buffer对象,xrange对象。
通用序列操作:
1)索引
greeting='Hello'print greeting[1]
2)分片
numbers=[1,2,3,4,5,6,7,8,9,10]print numbers[0:10:2]#[1, 3, 5, 7, 9]
3)序列相加
print [1,2,3]+[4,5,6]#[1, 2, 3, 4, 5, 6]
4)乘法
print 'Python '*3#Python Python Python
5)成员资格
permissions='rw'print 'w' in permissions# True
6)长度,最小值,最大值
numbers=[11,21,31]print len(numbers)print max(numbers)print min(numbers)# 3# 31# 11
列表:Python的‘苦力’
1)由字符串创建列表(list函数)
print list('hello')# ['h', 'e', 'l', 'l', 'o']
列表的基本操作
1)改变列表:元素赋值
>>> x=[1,1,1]>>> x[1]=2>>> x[1, 2, 1]2)删除元素
>>> names=['zhou','wei']>>> del names[1]>>> names['zhou']3)分片赋值
>>> name=list('Perl')>>> name['P', 'e', 'r', 'l']>>> name[2:]=list('haha')>>> name['P', 'e', 'h', 'a', 'h', 'a']
1)append
>>> lst=[1,2,3]>>> lst.append(4)>>> lst[1, 2, 3, 4]>>> lst.append('zhou')>>> lst[1, 2, 3, 4, 'zhou']2)count
>>> ['to','be','or','not','to','be'].count('to')2>>>3)extend
>>> a=[1,2,3]>>> b=[4,5,6]>>> a.extend(b)>>> a[1, 2, 3, 4, 5, 6]4)index
>>> ['to','be','or','not','to','be'].index('or')2>>>5)insert
>>> numbers=[1,2,3,4,5]>>> numbers.insert(2,'zhouwei')>>> numbers[1, 2, 'zhouwei', 3, 4, 5]6)pop
>>> x=[1,2,3]>>> x.pop()3>>> x[1, 2]>>> x.pop(0)1>>> x[2]
7) remove(删除第一个匹配项)
>>> numbers=['to','be','or','not','to','be']>>> numbers.remove('to')>>> numbers['be', 'or', 'not', 'to', 'be']>>>
8)reverse
>>> x=[1,2,3]>>> x.reverse()>>> x[3, 2, 1]>>>
9)sort
>>> x=[4,3,2,1]>>> x.sort()>>> x[1, 2, 3, 4]>>>
10) 高级排序
>>> x=['zhouwei','zhou','wei']>>> x.sort(key=len)>>> x['wei', 'zhou', 'zhouwei']>>> x.sort(reverse=True)>>> x['zhouwei', 'zhou', 'wei']>>>
tuple函数
>>> tuple('zhou')('z', 'h', 'o', 'u')>>>
format="hello, %s, %s, enough for yo?"values=('world','Hot')print format % values#hello, world, Hot, enough for yo?字符串方法
1)find
>>> 'zhouwei,nihao'.find('ni')8>>>2)join(反过程:split)
>>> seq=['1','2','3','4']>>> sep='+'>>> sep.join(seq)'1+2+3+4'>>>3)lower
>>> 'ZhouWei'.lower()'zhouwei'>>>
4) replace
>>> 'This is the test'.replace('is','eez')'Theez eez the test'>>>
第四章:字典:当索引不好用时
字典(mapping,dict)是Python中唯一内建的映射类型。字典中没有特殊的顺序,key可以使数字,字符串或元祖。
>>> items=[('name','zhouwei'),('age',42)]>>> d=dict(items)>>> d{'age': 42, 'name': 'zhouwei'}>>> d['name']'zhouwei'>>> x={}>>> x['name']='zhouwei'>>> x['name']'zhouwei'>>>字典的格式化字符串
phonebook={'Beth':'9123','Alice':'2234','cecil':'324'}print "Ceil's phone number is %(cecil)s."%phonebook# Ceil's phone number is 324.
Pyton 多线程实现机制
python是支持多线程的,并且是native的线程。主要是通过thread和threading这两个模块来实现的. 本文提供多线程实现的两种方式及让多条命令并发执行的代码样例
# Filename: thread-extends-class.py# 直接从Thread继承,创建一个新的class,把线程执行的代码放到这个新的 class里import threadingimport time class ThreadImpl(threading.Thread): def __init__(self, num): threading.Thread.__init__(self) self._num = num def run(self): global total, mutex # 打印线程名 print threading.currentThread().getName() for x in xrange(0, int(self._num)): # 取得锁 mutex.acquire() total = total + 1 # 释放锁 mutex.release() if __name__ == '__main__': #定义全局变量 global total, mutex total = 0 # 创建锁 mutex = threading.Lock() #定义线程池 threads = [] # 创建线程对象 for x in xrange(0, 40): threads.append(ThreadImpl(100)) # 启动线程 for t in threads: t.start() # 等待子线程结束 for t in threads: t.join() # 打印执行结果 print total
# encoding=utf-8# Filename: thread-function.py# 创建线程要执行的函数,把这个函数传递进Thread对象里,让它来执行 import threadingimport time def threadFunc(num): global total, mutex # 打印线程名 print threading.currentThread().getName() for x in xrange(0, int(num)): # 取得锁 mutex.acquire() total = total + 1 # 释放锁 mutex.release() def main(num): #定义全局变量 global total, mutex total = 0 # 创建锁 mutex = threading.Lock() #定义线程池 threads = [] # 先创建线程对象 for x in xrange(0, num): threads.append(threading.Thread(target=threadFunc, args=(100,))) # 启动所有线程 for t in threads: t.start() # 主线程中等待所有子线程退出 for t in threads: t.join() # 打印执行结果 print total if __name__ == '__main__': # 创建40个线程 main(40)
# encoding=utf-8# Filename: put_files_hdfs.py# 让多条命令并发执行,如让多条scp,ftp,hdfs上传命令并发执行,提高程序运行效率import datetimeimport osimport threading def execCmd(cmd): try: print "命令%s开始运行%s" % (cmd,datetime.datetime.now()) os.system(cmd) print "命令%s结束运行%s" % (cmd,datetime.datetime.now()) except Exception, e: print '%s\t 运行失败,失败原因\r\n%s' % (cmd,e) if __name__ == '__main__': # 需要执行的命令列表 cmds = ['ls /root', 'pwd',] #线程池 threads = [] print "程序开始运行%s" % datetime.datetime.now() for cmd in cmds: th = threading.Thread(target=execCmd, args=(cmd,)) th.start() threads.append(th) # 等待线程运行完毕 for th in threads: th.join() print "程序结束运行%s" % datetime.datetime.now()
PEP8:Python编程规范;
http://legacy.python.org/dev/peps/pep-0008/
Python 开源框架,
Python 服务器原型开发
http://ciniao.me/article.php?id=9
http://ciniao.me/article.php?id=10
http://blog.csdn.net/taozc/article/details/7532785
先把Python网络编程给大体看了,练习几个例子,具体网络编程见:《Foundations of Python network programming.djvu》
有关Python Twisted网络编程框架的书《Twisted Network Programming Essentials》官网:https://twistedmatrix.com/trac/
sock模块
https://docs.python.org/2/library/socket.html
urllib和urllib2模块
https://docs.python.org/2/library/urllib.html
https://docs.python.org/2/library/urllib2.html
SocketServer模块
https://docs.python.org/2/library/socketserver.html#module-SocketServer
Asyncore和Asynchat模块的介绍(标准库中事件驱动型框架,select和poll)
https://docs.python.org/2/library/asyncore.html
https://docs.python.org/2/library/asynchat.html#module-asynchat
HTMLParser
https://docs.python.org/2/library/htmlparser.html
cgi
http://www.w3cschool.cc/python/python-cgi.html
https://docs.python.org/2/library/cgi.html
https://docs.python.org/2/library/cgitb.html
- 【python】:python学习笔记
- Python学习笔记-Python起步
- Python学习笔记-Python基础
- Python学习笔记-Python对象
- Python基本概念--Python学习笔记
- Python学习笔记:Python函数
- python学习笔记-python安装
- Python学习笔记--Python基础
- 【Python】python基础学习笔记
- python学习笔记3
- Python学习笔记
- Boost.Python学习笔记
- python学习笔记1
- python学习笔记2
- python学习笔记(2)
- Python学习笔记 Module
- Python学习笔记.
- python学习笔记(1)
- LeetCode-Trapping Rain Water
- 页面置换算法
- 详解OD脚本的写法续之进阶篇
- 实习之旅
- Python polymorphism
- Python学习笔记
- Trie树+并查集+欧拉回路poj2513
- python 简单实现 图片百叶窗效果
- (转载)JAVA MVC初了解
- 进步,从CSDN博客开始
- 深入理解计算机系统之虚拟存储器
- 一元多项式的表示及相加(抽象数据类型Polynomial的实现)
- 140815暑期培训.txt
- 实现算法2.20、2.21的程序