第三天
1:列表及Python基础回顾
2:字典 列表字典生成式及应用场景
3:字符串 字典字符串转换及应用场景
4:文件操作 文件字典转换及应用场景
5:总结基础数据结构的知识脑图 -- 增删查改
1、列表的操作:
help(list) 列表的帮助,列出所有列表的用法
type(name) 判断数据类型是列表,元组或字典
1.1、增
>>> shoplist = [‘apple‘,‘mango‘,‘carrot‘,‘banana‘] >>> shoplist.append(‘rice‘) #方法1 列表尾部追加元素 >>> shoplist.insert(1,‘pear‘) #方法2 列表第二个位置插入元素 >>> shoplist [‘apple‘, ‘pear‘, ‘mango‘, ‘carrot‘, ‘banana‘, ‘rice‘]
1.2、删
>>> del shoplist[0] #方法1 根据索引删除列表中元素 >>> shoplist [‘pear‘, ‘mango‘, ‘carrot‘, ‘banana‘, ‘rice‘] >>> shoplist.remove(‘rice‘) #方法2 根据内容删除元素 >>> shoplist [‘pear‘, ‘mango‘, ‘carrot‘, ‘banana‘] >>> shoplist.pop() #方法3 弹出最后一个元素 ‘banana‘ >>> shoplist [‘pear‘, ‘mango‘, ‘carrot‘]
1.3、改
>>> shoplist [‘pear‘, ‘mango‘, ‘carrot‘] >>> shoplist[0] = ‘watermelon‘ #通过索引修改 >>> shoplist [‘watermelon‘, ‘mango‘, ‘carrot‘]
1.4、查
>>> num = [1,2,3,4,5,2] >>> len(num) #查看列表元素个数 6 >>> max(num) #查看列表中元素最大值 5 >>> min(num) #查看列表中元素最小值 1 >>> num.count(2) #查看列表中某元素个数 2 >>> num.index(3) #根据元素查找索引 2
2、列表的遍历
>>> for i in shoplist: ... print i ... pear mango carrot banana rice >>> for i,j in enumerate(shoplist): ... print i,j ... 0 pear 1 mango 2 carrot 3 banana 4 rice
3、split()和join(),字符串和列表的转换
>>> ip = ‘192.168.1.1‘ >>> ip.split(‘.‘) [‘192‘, ‘168‘, ‘1‘, ‘1‘] >>> l = [‘hello‘,‘world‘,‘!‘] >>> ‘ ‘.join(l) ‘hello world !‘
4、列表生成式
格式:
[ x for x in 内容]
[ x for x in 内容 if 条件]
1、把要生成的元素 x 放到前面,执行的时候,先执行后面的for循环
2、后面跟上for循环,可以有多个for循环,也可以在for循环后面再加个if条件
3、for循环后面可以是任何方式的迭代器(元组,列表,生成器..),只要可迭代对象的元素中至少有一个值.
>>> [x for x in ‘abcd‘] #单循环列表生成式 [‘a‘, ‘b‘, ‘c‘, ‘d‘] >>> l = range(10,15) >>> l [10, 11, 12, 13, 14] >>> [x for x in l if x > 12] #带if判断的单循环列表生成式 [13, 14] >>> [m+n for m in ‘abc‘ for n in ‘ABC‘] #双循环列表生成式 [‘aA‘, ‘aB‘, ‘aC‘, ‘bA‘, ‘bB‘, ‘bC‘, ‘cA‘, ‘cB‘, ‘cC‘] >>> A = [‘HELLO‘,‘WORLD‘,‘APPLE‘] #大小写转换 >>> [x.lower() for x in A] [‘hello‘, ‘world‘, ‘apple‘] >>> d = {‘name‘:‘Alice‘,‘age‘:20,‘gender‘:‘F‘} #迭代字典生成列表 >>> field = [k for k in d.keys()] >>> value = [v for v in d.values()] >>> field,value ([‘gender‘, ‘age‘, ‘name‘], [‘F‘, 20, ‘Alice‘])
5、字典生成式
格式:
1、在python2.6或更早的版本,字典生成器可以接受迭代的键值对
d = dict((k,v) for (k,v) in iterable)
2、在python2.7或3以后,可以直接使用字典推导式语法
d = {k:v for k,v in iterable}
3、python2.7以上兼容两种写法,python2.6只能使用第一种
4、可以用任何方式的迭代器(元组,列表,字典...),只要可迭代对象的元素中有两个值
>>> shoplist [‘pear‘, ‘mango‘, ‘carrot‘, ‘banana‘] >>> dict((k,v) for k,v in enumerate(shoplist)) {0: ‘pear‘, 1: ‘mango‘, 2: ‘carrot‘, 3: ‘banana‘} >>> {k:v for k,v in enumerate(shoplist)} {0: ‘pear‘, 1: ‘mango‘, 2: ‘carrot‘, 3: ‘banana‘}
1、嵌套元组和嵌套类别可以直接通过dict命令转为字典(嵌套内部的元素只能是2个)
>>> a = [(1,‘a‘),(2,‘b‘)] >>> dict(a) {1: ‘a‘, 2: ‘b‘}
2、zip()函数可以将多个元组或列表合并,合并规则是每个元组元素个数一致
>>> zip((‘name‘,‘age‘),(‘Bob‘,20)) [(‘name‘, ‘Bob‘), (‘age‘, 20)] >>> zip([‘name‘,‘age‘],[‘Bob‘,20]) [(‘name‘, ‘Bob‘), (‘age‘, 20)] >>> dict(zip((‘name‘,‘age‘),(‘Bob‘,20))) {‘age‘: 20, ‘name‘: ‘Bob‘} >>> zip((‘name‘,‘age‘),(‘Bob‘,20,‘F‘)) #元素个数不一致时,以最少的列表为准 [(‘name‘, ‘Bob‘), (‘age‘, 20)]
6、文件操作
open():
open(‘path‘): 默认只读打开
open(‘path‘,‘r+‘): 读写打开,如果有内容,就会从头覆盖相应字符串的内容
open(‘path‘,‘w‘): 写入,先删除源文件,重新写入
open(‘path‘,‘w+‘): 读写,同上
open(‘path‘,‘a‘): 写入,在文件末尾追加新内容,文件不存在就先创建
open(‘path‘,‘a+‘): 读写,同上
open(‘path‘,‘b‘): 打开二进制文件,多用于读取图片
open(‘path‘,‘U‘): 支持所有换行符号值\r\n\r\n
write():write(str)的参数是字符串
writelines():writelines(sequence)的参数是序列,比如列表,它会帮你迭代写入
read():每次读取整个文件,试用于小文件
readline():每次读一行,逐行读取
readlines():全部读取,自动将文件内容分析成一个行的列表,可以使用for...in...结构进行读取
close(): 关闭打开的文件
7、格式化
7.1 字符串格式化
>>> print ‘hello,%s‘%‘world‘ # 方法1:C格式 hello,world >>> print ‘hello,{}‘.format(‘world‘) # 方法2:C#格式 hello,world >>> print ‘hello,{1}{0}‘.format(‘!‘,‘world‘) # 方法3:C#格式 hello,world!
C#格式的优点是可以使用{0},{1},...{n}来匹配对应的参数,如上面的方法3
注:C#格式仅Python2.7以上版本可以使用
7.2、列表格式化
>>> msg = [‘name‘,‘Alice‘] >>> print ‘%s:%s‘%(msg[0],msg[1]) # 方法1:C格式 name:Alice >>> print ‘%s‘%‘:‘.join(msg) # 方法2:C格式(推荐使用) name:Alice >>> print ‘%s%s:%d‘%(‘her ‘,‘age‘,20) # 方法3:C格式 >>> print ‘{} is {}‘.format(*msg) # 方法4:C#格式 name is Alice >>> print ‘{}{}{}‘.format(‘hello ‘,‘world ‘,‘!‘) # 方法5:C#格式 hello world !
注:C#格式仅Python2.7以上版本可以使用
7.3、字典格式化
>>> d = {‘name‘:‘Alice‘,‘age‘:18} >>> print ‘I am %(name)s,my age is %(age)d‘%d # 方法1 I am Alice,my age is 18 >>> print ‘I am {name},my age is {age}‘.format(**d) # 方法2(推荐使用) I am Alice,my age is 18 >>> print ‘I am {name},my age is {age}‘.format(name=‘Alice‘,age=18) # 方法3 I am Alice,my age is 18
8、字符串处理常用方法:startswith()、endswith和strip()
startswith():判断是否以指定子串开始
endswith():判断是否以指定子串结束
>>> a = ‘hello‘ >>> a.startswith(‘a‘) False >>> a.startswith(‘h‘) True >>> a.startswith(‘he‘) True >>> a.endswith(‘o‘) True >>> a.endswith(‘lo‘) True >>> a.endswith(‘l‘) False
strip():删除字符串开始和结尾处的指定的字符,默认为空格
rstrip():删除字符串结尾处指定的字符
lstrip():删除字符串开始处指定的字符
>>> string = ‘ aaabb cc ‘ >>> string.strip() ‘aaabb cc‘ >>> string.rstrip() ‘ aaabb cc‘ >>> string.lstrip() ‘aaabb cc ‘ >>> string2 = ‘aabbccd‘ >>> string2.strip(‘a‘) ‘bbccd‘ >>> string2.strip(‘d‘) ‘aabbcc‘
练习:
1、将主机ip(192.168.1.1-254)存入列表
hostlist = [] netip = ‘192.168.1.‘ for hostip in range(1,255): ip = netip + str(hostip) hostlist.append(ip) print hostlist
2、将这个字典逐个显示{‘name‘:‘Alice‘,‘Bob‘:[‘male‘,20],‘Tom‘:{‘age‘:25,‘gender‘:‘M‘}}
d = {‘name‘:‘Alice‘,‘Bob‘:[‘male‘,20],‘Tom‘:{‘age‘:25,‘gender‘:‘M‘}} for k,v in d.items(): print k+‘:‘ # if type(v) is list: if isinstance(v,list): for i in v: print i # elif type(v) is dict: elif isinstance(v,dict): for m,n in v.items(): print m,n else: print v
3、将一段文本拼接成num:word的字典格式
content="who have touched their lives Love begins with a smile grows with a kiss and ends with a tear The brightest future will always be based on a forgotten past you can not go on well in life until you let go of your past failures and heartaches"
content="who have touched their lives Love begins with a smile grows with a kiss and ends with a tear The brightest future will always be based on a forgotten past you can not go on well in life until you let go of your past failures and heartaches" d = {} for word in content.split(): #将字符串转化为word:num格式 if word in d.keys(): d[word] += 1 else: d[word] = 1 print d d2 = {} #将k,v互换,为num:list(word)格式 for word,count in d.items(): d2.setdefault(count,[]) d2[count].append(word) print d2
4、通过文本,构建一个注册,登陆系统
4.1、注册系统
#!/usr/bin/python #-coding = utf-8- fo = open(‘user.txt‘,‘a+‘) while True: name = raw_input(‘Please Input your name: ‘).strip() passwd = raw_input(‘Please Input your password: ‘).strip() repasswd = raw_input(‘Please Input your password again: ‘).strip() if not name: print ‘The name can not be null‘ #用户名不能为空 continue elif not passwd or passwd!=repasswd: #密码不能为空,且与再次输入相同 print ‘Wrong password‘ continue else: print ‘login successfully‘ break fo.write(‘%s:%s\n‘%(name,passwd)) #写入文件 fo.close()
4.2、登陆系统
#!/usr/bin/python #-coding=utf-8- fo = open(‘user.txt‘) #读取文件 content = fo.readlines() fo.close() d = {} for user in content: name = user.strip(‘\n‘).split(‘:‘)[0] #获取用户名和密码 passwd = user.strip(‘\n‘).split(‘:‘)[1] d[name] = passwd #print d count = 0 while True: count += 1 if count > 3: print ‘Sorry,too many error you input,contact the administrator please‘ break #输入出错超过3次,退出 name = raw_input(‘Please input your name: ‘) passwd = raw_input(‘Please input your passwd: ‘) if not name: #对输入的用户名,密码进行判断 print ‘Name can not be null‘ continue elif name not in d: print ‘No such user‘ continue elif not passwd or passwd!=d[name]: print ‘Wrong password‘ continue else: print ‘login successfully‘ break
5、从一段nginx访问日志中,获取前十个访问次数最多的ip地址,生成html文件显示
#!/usr/bin/python #-coding:utf-8- fo = open(‘access.log‘) content = fo.readlines() fo.close() #从字符串转化为列表 l = [] d = {} for msg in content: ipaddr = msg.split(‘ ‘)[0] l.append(ipaddr) #print l #从列表转化为字典 for ipaddr in l: if ipaddr in d: d[ipaddr] += 1 else: d[ipaddr] = 1 d2 = {v:k for k,v in d.items()} #print d2 #找出访问频率最高的前十个ip地址,保存为html格式 count = 0 f = open(‘access.html‘,‘a+‘) f.write("<html><table style=‘border:solid 1px‘>") f.write("<th style=‘border:solid 1px‘>访问次数</th><th style=‘border:solid 1px‘>ip地址</th>") while count < 10: key = max(d2.keys()) # print "出现了%s次的ip地址:%s" % (key,d2[key]) f.write(‘<tr><td style="border:solid 1px">%s</td><td style="border:solid 1px">%s</td></tr>‘ % (key,d2[key])) d2.pop(key) count = count +1 f.write("</table></html>") f.close()
html文件效果图:
原文地址:http://11001353.blog.51cto.com/10991353/1827462