Python_2

1. 生成器,使用一次后清空;

L = (x*x for x in range(10))

2. 迭代器,可用于for循环的叫可迭代对象;可被next()调用并不断返回下一个值的叫迭代器;

可用isinstance来判断

from collections import Iterable,Iterator

a = [1,2,3,4]

isinstance(a,Iterable)

3. 高阶函数:

len([1,2,3,4])

x = len

x([1,2,3])  #函数可以被拿来当做参数使用

4. map接受两个参数,一个函数,一个可迭代是对象,返回可迭代对象;函数作用在每个元素上;

x = [1,2,3]

list(map(lambda s: s*s,x))  ——[1,4,9]

5. reduce接受两个参数,函数有两个参数,将元素与下一个累积计算

from functools import reduce 

reduce(lambda a,b: a-b,x) —— -4

6. filter 作用在序列元素上,返回结果是布尔型,根据true或false进行保留或删除;

x = [1,2,3,4,5,6]

list(filter(lambda s: s%2==0 or s%3==0,x))

7. 匿名函数

8.类,python3以上如下写法

class Student:

kind = "Chinese"

def __init__(self,student_id,address,score,student_name):

        self.student_id = id

        self.address = address

        self.score = score

        self.student_name = name

    def getId(self):

        print(self.student_id)

student = Student(10200,"Beijing",98,"xiaomi")

9. 

class Student():

    def __init__(self,id,name):

       self.id = id

       self.name = name

def getname(self):

    print(self.name)

class Highschool(Student):

    pass

Highschool(12345,"xiaoming")

10. collections类

——deque  #对序列两端进行操作

from collections import deque

a = (x*x for x in range(100))

a.rotate()

a.dequeleft(111)

%timeit deque.a.append(100)

——counter  #计数

a = list("abcdfefebdsa")

c = a.counter("a")

a.most_commom(5) 

——OrderedDict

from collections import OrderedDict

d = {'banana':3,'apple':4,'pear':5,'orange':2}

OrderedDict(sorted(d.items(),key = lambda s: s[0]))  #对key排序

OrderedDict(sorted(d.items(),key = lambda s: s[1]))  #对value排序

10. #字符串处理

s = 'hello world '

s.strip() #去除首位空格

s.find('o')  #找'o'首次在字符串中出现的位置

s.endwith('o')  ——False

s.split(" ")  ——切割

11. #格式化

——

a = "shanghai"

b = 33

print("今天 {0} 的气温是 {1}".format(a,b))

——

for i in range(100):

    t = str(i)

    print("这是我打印的第 %s 个数"%t)

12. #datatime

from datatime import datatime, timedelta

s = "20190703"

——s1 = datatime.strptime(s,"%Y%m%d")

s =  "2019/06/06

——s2 = datatime.strptime(s,"Y/m/d")

——s2 -s1

——s1 + timedelta(days = 3) + timedelta(hours = 3)

13. # I/O

——

f = open("file","r")

data = f.read

f.close

——

with open("file") as handle:

    data = handle.readlines()  #整合前面的语句

——

f = open("file","r",encoding = "gbk")   #utf-8

——

with open("file","a") as handle:

    handle.write("Hello,worle\n")

     handle.write("Hello, soton")  #a为附加到文件,如果写w,会覆盖原文件内容

14.  #异常处理

——

try:

    c = a/b

except ZeroDivisionError:

    print("除数不能为0")

else:

    print(c)

print(c)

——

filename = file.text

try:

    withopen(filename,"r") as handle:

        data = handle.read()

except FileNotFindError:

    mes = "Sorry, not find" + filename

    print(mes)

你可能感兴趣的:(Python_2)