1. print repr(u'中国') 的运行结果是什么?
解:u'\u4e2d\u56fd'
2. 什么是lambda函数?并列举一个使用lambda函数的例子
解:lambda是python中快速定义单行函数的一种方式,lambda需要一个参数,后面仅跟单个表达式作为函数体(注意只能跟单个表达式,即使是print语句也不能用在lambda形式中,后面只能跟单个表达式),表达式的值被这个新建的函数返回。
3. Excel操作
将
{
"1":["张三",150,120,100],
"2":["李四",90,99,95],
"3":["王五",60,66,68]
}
写入excel如下所示:
解:需要用到一个对excel进行写操作的第三方库xlwt,需要提前下载安装。具体操作很简单,就是两个for循环。注意中文字符的处理,需要先定义编码格式,如果用的是IDE,还需要设置好编辑器的编码格式。
#coding=utf-8
import xlwt
file=xlwt.Workbook()
table=file.add_sheet('Students')
data = {
'1':[u'张三',150,120,100],
'2':[u'李四',90,99,95],
'3':[u'王五',60,66,68]
}
for key in data.keys():
table.write(int(key)-1,0,int(key))
for i in range(0,len(data[key])):
table.write(int(key)-1,i+1,data[key][i])
file.save('Students.xls')
4. 简述对Python装饰器的理解,写一个简单的装饰器。
答:装饰器的作用就是可以在函数执行前或执行后附加额外的功能。
#coding=utf-8
def deco(func):
print 'before myfunc() called.'
func()
print 'after myfunc() called.'
return func
def myfunc():
print 'myfunc() called'
myfunc=deco(myfunc)
当然也可以用语法糖@
#coding=utf-8
def deco(func):
print 'before myfunc() called.'
func()
print 'after myfunc() called.'
return func
@deco
def myfunc():
print 'myfunc() called'
上面两段程序所实现的功能一样。运行结果:
5. 生成100个随机数,保存到Redis非关系型数据库中。
解:注意首先要在windows下面安装并开启redis服务,然后python安装第三方的redis库。
import random
import redis
r=redis.StrictRedis(host='localhost',port=6379)
for i in range(100):
r.set(i, random.randint(1,1000))
a=[r.get(i) for i in range(100)]
print a
运行结果:
6.写结果,说明原因
if 1 in [1,0] ==True:
print ‘a’
else:
Print ‘b’
解:会输出 b。在python中 1 in [1,0] == True会被转化为:(1 in [1,0]) and ([1,0]==true) Ture and False==False
7. 用Python写一个程序,拉取SVN上的某一个文件,修改后并提交该文件。
#coding=utf-8
import os
os.system('svn co https://code.bk.tencent.com/apps/campus/testtest/trunk</span> test --username=XXXXX --password=XXXXX') (XXXXX分别为svn的地址 用户名和密码)
name = raw_input('Please input file name: ')
name='test/'+name;
f=open(name,'r')
allLines=f.readlines()
f.close()
for i,eachline in enumerate(allLines):
print '%2d>>%s'%(i+1,eachline)
count = 0
while(count<5):
allLines[count]=raw_input('new input:')+'\n'
count=count+1
newfile=open(name,'w')
for x in allLines:
newfile.write(x)
newfile.close()
print '\nrewrite over',
os.system('svn commit -m --force-log "test\\requirements.txt"')
os.system('svn ci -m "b" %s --username XXXXX --password XXXXX')#XXXXX(自己的用户名和密码)
运行结果图:
可以看出svn拉取成功,并修改了requirements.txt的内容,并上传成功。去代码管理的网站上看看确实修改成功。
8. 用Python画出y=x3的散点图。
解:需要安装Matplotlib以及一系列的依赖包。
import pylab as pl
x=pl.np.linspace(-10,10,256)
x3=lambda x:x*x*x
pl.plot(x,x3(x))
ax=pl.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))
ax.set_yticks([-1000,-500,500,1000])
pl.xlim(x.min()*1.2,x.max()*1.2)
pl.show()
9. 用Python爬取知乎热门帖的标题,并存储到MySQL中
解:需要先创建好test数据库和test表格,然后进行操作。注意如果在cmd下显示乱码,在cmd下打开数据库之后,输入命令 set names ‘gbk’,然后就会显示正常。
#coding=utf-8
import urllib2
import re
import MySQLdb
conn=MySQLdb.connect(host='localhost',db='test',port=3306,charset='utf8')
cur=conn.cursor()
url='http://www.zhihu.com/topic/19607535/top-answers'
file=urllib2.urlopen(url).read()
print file
list=re.findall('<a class="question_link"(.*?)/a>',file,re.S)
p='>(.*?)<'
print list
for x in list:
title=re.search(p,x,re.S).group(1)
cmd="insert into test(title) values('%s')" % title
print cmd
cur.execute(cmd)
conn.commit()
conn.close()
10.Python 中 数组套字典的排序(用lambda实现)
dict = [
{'id':'4','name':'b'},
{'id':'6','name':'c'},
{'id':'3','name':'a'},
{'id':'1','name':'g'},
{'id':'8','name':'f'}
]
排序后:[{'id': '1', 'name': 'g'}, {'id': '3', 'name': 'a'}, {'id': '4','name': 'b'}, {'id': '6', 'name': 'c'}, {'id': '8', 'name': 'f'}]
解:dict=[
{'id':'4','name':'b'},
{'id':'6','name':'c'},
{'id':'3','name':'a'},
{'id':'1','name':'g'},
{'id':'8','name':'f'}
]
dict=sorted(dict,key=lambda x:x['id'])
print dict
其中dict.sort和sorted那两条语句实现的功能相同,dict.sort中传入的是一个比较函数,sorted那条语句表示,在对dict中的各个元素进行排序之前,各个元素先调用key所指定的函数,然后再比较。
其实直接用dict.sort(cmp)也可以,因为用cmp()函数对字典进行比较时,是先比较字典长度,在比较字典的键,然后比较字典的键值,在dict中各个字典长度相等,字典的键也相等,所以就直接比较字典的值,对字典中每个相同的键多对应的值进行比较,一旦出现不匹配的值,就对这两个值进行直接比较。很显然直接用cmp()函数也可以实现同样的功能,但是题目要求用lambda,所以用上面两种方式实现。
运行结果:
11.利用python计算文件MD5值。
解:对于大文件,不能一次性载入内存,需要对文件分片然后不停的update完成。
#coding=utf-8
import hashlib
import os
def GetMD5(filename):
myhash=hashlib.md5()
f=file(filename,'rb')
while True:
b=f.read(8096)
if not b:
break
myhash.update(b)
f.close()
return myhash.hexdigest()
filepath=raw_input('请输入文件路径: ')
print GetMD5(filepath)
运行结果:可以去这个网站上检查文件的MD5值来看你的程序是否运行正确:http://www.atool.org/file_hash.php
12.密码加密小工具
(对于部分喜欢将自己密码存在邮箱、网盘等容易被盗的朋友,可以自己记住一个唯一的密钥,通过这个小程序和密钥产生一串加密密文再存储,减少密码被盗几率。提示:Crypto库 a.输入自己的秘钥:123456, b.选择是: encrypt 或者decrypt, c. 输出:加密后的密文,或者解密后的明文)
解:加密文本是以16个字节为单位的,把文本分成好多个16字节的文本段进行加密,如果最后剩余的文本段不足16个字节,就用‘\0’补足。
#coding=utf8
import sys
from Crypto.Cipher import AES
from binascii import b2a_hex,a2b_hex
class prpcrypt():
def __init__(self,key):
self.key=key
self.mode=AES.MODE_CBC
def encrypt(self,text):
cryptor=AES.new(self.key,self.mode,self.key)
length=16
count=len(text)
add=length-(count%16)
text=text+('\0'*add)
self.ciphertext=cryptor.encrypt(text)
return b2a_hex(self.ciphertext)
def decrypt(self,text):
cryptor=AES.new(self.key,self.mode,self.key)
plain_text=cryptor.decrypt(a2b_hex(text))
return plain_text.rstrip('\0')
if __name__ == '__main__':
pc=prpcrypt('keyskeyskeyskeys')
e=pc.encrypt("00000")
d=pc.decrypt(e)
print e,d
e=pc.encrypt("00000000000000000000000000")
d=pc.decrypt(e)
print e,d
运行结果: