7 Jun 18 复习,文件,函数,sorted,colletions

7 Jun 18 复习,文件,函数,sorted,colletions

一、文件

‘r'open for reading (default)

‘w'open for writing, truncating the file first

‘a'open for writing, appending to the end of the file if it exists

‘b'binary mode

‘t'text mode (default)

‘+'open a disk file for updating (reading and writing)

‘U'universal newline mode (for backwards compatibility; should not be used in new code)

二、函数

扫描二维码关注公众号,回复: 1515327 查看本文章

1、函数在定义阶段:只检测语法,不执行代码

2、函数是第一类对象,即函数可以当作数据传递

#1 可以被引用

#2 可以当作参数传递

#3 返回值可以是函数

#4 可以当作容器类型的元素

3、名称空间的加载顺序

#1、python解释器先启动,因而首先加载的是:内置名称空间

#2、执行test.py文件,然后以文件为基础,加载全局名称空间

#3、在执行文件的过程中如果调用函数,则临时产生局部名称空间

4、可迭代对象:内置有__iter__方法的

5、迭代器对象:obj.__iter__()得到的结果;既有__iter__方法,又有__next__方法

6、生成器:函数内部含有yield关键字,那么函数名()得到的结果就是生成器,并且不会执行函数内部的代码

7、生成器就是迭代器

8、把列表推导式的[]换成()就是生成器表达式

三、sorted

sort 与sorted 区别:

sort 是应用在 list 上的方法,sorted 可以对所有可迭代的对象进行排序操作。

list 的sort 方法返回的是对已经存在的列表进行操作,而内建函数sorted 方法返回的是一个新的list,而不是在原来的基础上进行的操作。

>>>a = [5,7,6,3,4,1,2]

>>> b = sorted(a)       # 保留原列表

>>> a 

[5, 7, 6, 3, 4, 1, 2]

>>> b

[1, 2, 3, 4, 5, 6, 7]

>>> L=[('b',2),('a',1),('c',3),('d',4)]

>>> sorted(L, cmp=lambda x,y:cmp(x[1],y[1]))   # 利用cmp函数

[('a', 1), ('b', 2), ('c', 3), ('d', 4)]

>>> sorted(L, key=lambda x:x[1])               # 利用key

[('a', 1), ('b', 2), ('c', 3), ('d', 4)]

  

>>> students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]

>>> sorted(students, key=lambda s: s[2])            # 按年龄排序

[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

>>> sorted(students, key=lambda s: s[2], reverse=True)       # 按降序

[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]

>>> 

四、collections(块提供了一些有用的集合类)

from collections import Counter

Counter是一个简单计数器,也是dict的一个子类;

import re

from collections import Counter

with open("xx.log","r",encoding="utf-8") as f:

   data=f.read()

ret=re.findall(r'https://(.*?)/.*?',data)

dic=Counter(ret)  # Counter({'www.bilibili.com': 4, 'www.sogo.com': 3, 'www.qq.com': 1, 'y.qq.com': 1, 'dig.chouti.com': 1})

ret2=sorted(dic.items(),key=lambda x:x[1],reverse=True)  # [('www.bilibili.com', 4), ('www.sogo.com', 3), ('www.qq.com', 1), ('y.qq.com', 1), ('dig.chouti.com', 1)]

for k,v in ret2:

   print(v,k)

猜你喜欢

转载自www.cnblogs.com/zhangyaqian/p/py201806070.html