摘要:

复习day2内容

介绍set()-->归档到day2了...

collections模块常用类

深浅copy的区别

自定义函数

文件操作

常用内建函数介绍

一、深浅copy的区别

 #! /usr/bin/env python
 # -*- coding: utf-8 -*-
 # __author__ = "Q1mi"

 """
 深浅copy的区别
 """

 import copy
 # 数字、字符串:赋值、浅拷贝和深拷贝无差别,因为其永远指向同一个内存地址。
 print("字符串的赋值".center(30, '*'))
 n1 = 123123
 n2 = n1
 print(id(n1))
 print(id(n2))

 print("字符串的赋值".center(30, '*'))
 n11 = '
 n22 = n11
 print(id(n11))
 print(id(n22))

 print("数字和字符串的浅copy".center(50, '*'))
 n3 = copy.copy(n1)
 print(id(n1))
 print(id(n3))

 print("数字和字符串的深copy".center(50, '*'))
 n4 = copy.deepcopy(n1)
 print(id(n1))
 print(id(n4))

 # 其他:除了数字和字符串以外,(多层)列表、字典、元祖等在进行赋值、浅copy、深copy时,内存地址是有区别的。
 print("其他类的赋值".center(50, '*'))
 m1 = {', 'k3': [1, 3, 5]}
 m2 = m1
 print(id(m1))
 print(id(m2))

 print("其他类的浅拷贝".center(50, '*'))
 print("浅copy".center(50, '*'))
 m3 = copy.copy(m1)
 print("id(m1):%s" % id(m1))
 print("id(m3):%s" % id(m3))
 # 浅拷贝的m3['k3']这一层指向了同一个内存地址
 print("id(m1['k3']):%s" % id(m1['k3']))
 print("id(m3['k3']):%s" % id(m3['k3']))

 print("其他类的深拷贝".center(30, '*'))
 print("深copy".center(30, '*'))
 m4 = copy.deepcopy(m1)
 print("id(m1):%s" % id(m1))
 print("id(m4):%s" % id(m4))
 # 深拷贝的m4['k3']这一层指向了不同的内存地址
 # 深拷贝就是将除了数字和字符串以外的都重新开辟一个内存空间
 print("id(m1['k3']):%s" % id(m1['k3']))
 print("id(m4['k3']):%s" % id(m4['k3']))

 # 应用:例如监控项配置的修改,要用深copy防止被copy的对象也被修改
 print('浅copy会改变被拷贝对象的值'.center(50, '*'))
 old_dic = {'cpu': [80, ], 'disk': [70], 'memory': [60]}
 # 浅copy之后,更改新字典的话,新旧字典一起更改
 new_dic = copy.copy(old_dic)
 new_dic['cpu'][0] = 50
 print("old_dic:%s" % old_dic)
 print("new_dic:%s" % new_dic)

 print('深copy不会改变被拷贝对象的值'.center(50, '*'))
 old_dic2 = {'cpu': [80, ], 'disk': [70], 'memory': [60]}
 # 深copy之后,更改新字典的话,新字典的值改变而旧字典的值不会变
 new_dic2 = copy.deepcopy(old_dic2)
 new_dic2['cpu'][0] = 50
 print("old_dic2:%s" % old_dic2)
 print("new_dic2:%s" % new_dic2)

深浅copy的代码示例

赋值相当于copy了0层,copy相当于copy了1层,deepcopy()相当于copy了多层。

二、自定义函数

 #! /usr/bin/env python
 # -*- coding: utf-8 -*-
 # __author__ = "Q1mi"

 """
 自定义的函数
 """

 # 无参数
 def sho():
     print("无参数函数")

 sho()

 # 一个参数
 # 注意:函数遇到return关键字就跳出了,所以下例中的print('b')并不会被执行
 def show(a):
     print(a)
     return [11, 22]
     print('b')
 result = show(333)
 print(result)
 print("分割线".center(30, '*'))

 # 两个参数
 def show0(a1, a2):
     print(a1)
     print(a2)
 show0(111, 333)

 # 默认参数
 def show1(a1, a2=555):
     print(a1)
     print(a2)
 show1(111)
 show1(111, 333)
 show1(a2=333, a1=111)

 # *args即代表传入的参数按照列表或元祖处理
 # 动态参数-元祖
 def show2(*args):
     print(args, type(args))

 show2(11, 22, 33, 44)

 # 动态参数-列表
 def show2(*args):
     print(args, type(args))

 show2([11, 22, 33, 44])
 l1 = [44, 55, 66, 77]
 show2(* l1)
 print('分割线-line:72'.center(30, '*'))

 # **kwargs代表传入的参数按照字典来处理
 # 动态参数-字典
 def show3(**kwargs):
     print(kwargs, type(kwargs))

 show3(n1=11, n2=22)

 # 动态参数-序列和字典
 def show4(*args, **kwargs):
     print(args, type(args))
     print(kwargs, type(kwargs))
 show4(11, 22, 33, n=44, m=55)

 # 注意:
 l = [11, 22, 33]
 d = {'n': 44, 'm': 55}
 # 直接传入会把l和d,传入*args
 show4(l, d)

 # 需要对传入的参数进行处理
 show4(*l, **d)

 # 用于字符串的格式化
 str_tmp = "{0} is {1}!"
 result = str_tmp.format('alex', 'humor')
 print(result)

 result = str_tmp.format(*['alex', 'humor'])
 print(result)

 str_tmp = "{name} is {actor}!"
 print(str_tmp.format(name='alex', actor='humor'))

 d_tmp = {'name': 'alex', 'actor': 'humor'}
 result = str_tmp.format(**d_tmp)
 print(result)

 # 简单函数lambda
 def func_tmp(a):
     return a+1
 result1 = func_tmp(99)
 print(result1)
 result2 = lambda a: a+1
 print(result2(99))

自定义函数的代码示例

三、collections模块常用类

 #! /usr/bin/env python
 # -*- coding: utf-8 -*-
 # __author__ = "Q1mi"

 """
 collections里常见的几个类
 """

 # Counter 计数器
 from collections import Counter
 c = Counter('afaafsdqadsa')
 print(c)

 # OrdereDict 有序字典:记住了字典元素添加的顺序
 from collections import OrderedDict
 dic_tmp = OrderedDict()
 dic_tmp['k1'] = 'v1'
 dic_tmp['k2'] = 'v2'
 dic_tmp['k3'] = 'v3'
 print(dic_tmp)
 print(type(dic_tmp))

 # defaultdict 默认字典:默认给字典的值设置一个类型
 from collections import defaultdict
 dic_tmp = defaultdict(list)
 dic_tmp['k1'] = 'v1'
 dic_tmp['k2'] = 'v2'
 dic_tmp['k3'] = 'v3'
 print(dic_tmp)
 print(type(dic_tmp))

 # namedtuple 可命名元祖
 from collections import namedtuple
 # 例如用于定义x,y,x轴等
 MyNamedtupleClass = namedtuple('MyNamedtupleClass', ['x', 'y', 'z'])
 namedtuple_tmp = MyNamedtupleClass(11, 22, 33)
 print(namedtuple_tmp.x)
 print(namedtuple_tmp.y)
 print(namedtuple_tmp.z)

 # deque 一个线程安全的双向队列:左右皆可进出
 from collections import deque
 deque_tmp = deque()
 deque_tmp.append((11, 22, 33))
 print(deque_tmp)
 deque_tmp.pop()

 # queue.Queue 单向队列:先进先出
 from queue import Queue
 queue_tmp = Queue()
 queue_tmp.put(11, 22, 33)
 print(queue_tmp)
 queue_tmp.get(11)

collections常见类

四、文件操作

文件句柄 = open('文件路径', '打开模式')

打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。

打开文件的模式有:

r,只读模式(默认)。
w,只写模式。【不可读;不存在则创建;存在则删除内容;】
a,追加模式。【可读; 不存在则创建;存在则只追加内容;】
"+" 表示可以同时读写某个文件

r+,可读写文件。【可读;可写;可追加】
w+,写读
a+,同a
"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)

rU
r+U
"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)

rb
wb
ab

 #! /usr/bin/env python
 # -*- coding: utf-8 -*-
 # __author__ = "Q1mi"

 """
 open()文件操作
 """

 f = open('open_ex_test.txt', 'r', encoding='utf-8')
 print(f.tell())
 # 按照字符读
 f.read(2)
 # tell()返回的是根据字节得到的位置
 print(f.tell())
 # seek()指定当前指针位置,seek()用的是字节
 # 由于有中文,所以把指针指向1,就会报错,因为一个中文包括三个字节
 # f.seek(1)
 # print(f.read())

 # truncate():把当前指针位置之前的数据保留下来,舍去后面的(需用a+模式)
 f.close()

文件操作

为防止打开文件后忘记关闭,可以使用with来操作文件。

 with open ('log.txt', 'r') as f:
     ...
     ...

with代码块结束后会自动关闭文件。

当然也可以同时操作多个。

 with open ('log1.txt', 'r') as f1, open ('log2.txt', 'r') as f2:
     pass

五、常用内置函数

 #! /usr/bin/env python
 # -*- coding: utf-8 -*-
 # __author__ = "Q1mi"

 """
 Python的内建方法
 """

 # abs(x):返回x的绝对值
 # all(iterable):所有元素为真,则返回真
 result = all([1, ''])
 print(result)
 result = all([1, 'a'])
 print(result)
 # any(iterable):有一个元素为真,则返回真
 result = any(('', [], ))
 print(result)
 result = any(('', [], 1))
 print(result)
 # ascii(object):返回一个可打印对象的字符串,忽略没有编码表示的字符串返回调用转义字符的repr()。
 # As repr(), return a string containing a printable representation of an object,
 # but escape the non-ASCII characters in the string returned by repr() using \x, \u or \U escapes.
 # This generates a string similar to that returned by repr() in Python 2.

 # bin(x): 返回x的二进制数
 result = bin(10)
 print(result)
 # bool(x):返回布尔值
 # bytearray([source[, encoding[, errors]]]):返回字节数组
 # Return a new array of bytes. The bytearray class is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that the bytes type has, see Bytes and Bytearray Operations.

 # The optional source parameter can be used to initialize the array in a few different ways:
 #
 # If it is a string, you must also give the encoding (and optionally, errors) parameters; bytearray() then converts the string to bytes using str.encode().
 # If it is an integer, the array will have that size and will be initialized with null bytes.
 # If it is an object conforming to the buffer interface, a read-only buffer of the object will be used to initialize the bytes array.
 # If it is an iterable, it must be an iterable of integers in the range 0 <= x < 256, which are used as the initial contents of the array.
 # Without an argument, an array of size 0 is created.

 result = bytearray('周杰伦', encoding='utf-8')
 print(result)
 # bytes():返回字节
 #
 result = bytes('周杰伦', encoding='utf-8')
 print(result)
 # callable():是否可调用
 # chr(i):返回Unicode码i代表的字符串 与ord()相反
 print(chr(95))
 # ord():返回字符串对应的Unicode码
 print(ord('_'))
 # classmethod(function):返回类方法
 # compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1):编译
 # complex([real[, imag]]:复数
 # delattr(object, name):删除属性
 # -This is a relative of setattr(). The arguments are an object and a string. The string must be the name of one of the object’s attributes. The function deletes the named attribute, provided the object allows it. For example, delattr(x, 'foobar') is equivalent to del x.foobar.
 # dict():创建字典
 # dir([object]):返回列表
 # -Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.
 # divmod(a, b):返回一个元祖(a//b, a%b)
 # enumerate(iterable, start=0):枚举
 # eval(expression, globals=None, locals=None):执行字符串类型的表达式,并返回结果
 result = eval('99+1')
 print(result)
 # exec(object[, globals[, locals]]):执行存储在字符串或文件中的Python语句
 result = exec("print(eval('99+1'))")
 print(result)
 # filter(function, iterable):筛选,用前面的function去筛选后面的,留下符合条件的。
 l1 = [11, 66, 33, 77, 22, 88, 44, 99]
 result = filter(lambda x: x > 50, l1)
 print(list(result))
 # float([x]):返回一个浮点数
 print(float('+1.23'))
 print(float('     -123456\n'))
 print(float('1e-003'))
 print(float('+1E6'))
 print(float('-Infinity'))
 # format(value[, format_spec]):字符串的格式化
 # -format_spec ::=  [[fill]align][sign][#][0][width][,][.precision][type]
 # -fill        ::=  <any character>
 # -align       ::=  "<" | ">" | "=" | "^"
 # -sign        ::=  "+" | "-" | " "
 # -width       ::=  integer
 # -precision   ::=  integer
 # -type        ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

 # frozenset([iterable]):冻结集合
 # getattr(object, name[, default])
 # globals()
 # hasattr(object, name)
 # hash(object):返回哈希值
 # help([object]):获取帮助信息
 # hex(x):十六进制数
 # id(object):返回ID
 # input([prompt]):获取输入
 # int():返回整数
 ', 2))
 ', 8))
 ', 10))
 ', 16))
 # isinstance(object, classinfo):返回是不是类实例
 # issubclass(class, classinfo):返回是不是父类
 # iter(object[, sentinel]):返回一个迭代器
 # len(s):返回对象的长度
 # list([iterable]):生成列表
 # locals():更新并返回一个本地符号表的字典
 # map(function, iterable, ...):将函数作用于迭代器每个对象的结果返回一个迭代器
 # max(iterable, *[,key, default]):返回最大值
 d1 = {'a': 10, 'c': 5, 'f': 3, 'b': 7}
 print(max(d1.items(), key=lambda t: t[1]))
 # -max(arg1, arg2, *args[,key])
 # memoryview(obj):返回一个给定参数的内存视图
 # min(iterable, *[,key, default]):返回最小值
 # -min(arg1, arg2, *args[,key])
 # next(iterator[, default])
 # object()
 # oct(x):八进制数
 # open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
 # ord()
 # pow(x, y[, z]):x的y次幂再对z求余数
 # print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False):打印
 # property()
 # range(stop)
 # -range(start, stop[, step])
 # repr(object)
 # reversed(seq):反转
 # round(number[, ndigits]):返回浮点数的四舍五入值。round(0.5)->0而round(1.5)->2
 # set([iterable]):集合
 # setattr(objEct,name, value):对应于getattr()
 # slice(stop):切片
 # -slice(start, stop[,step]):切片
 # sorted(iterable[,key][,reverse]):排序
 # staticmethod(function)
 # str(object='')
 # -str(object=b'', encoding='utf-8', errors='strict')
 # sum(iterable[, start]):求和
 # super([type[, object-or-type]])
 # tuple([iterable]):元祖
 # type(object):返回对象的类型
 # -type(name, bases, dict):返回一个新类型的对象
 # vars([object]):返回对象属性和属性值的字典
 # zip(*iterables):返回一个元素来自每一个迭代器的迭代器
 # __import__():被import声明调用的一个方法

内置函数

点此查看官方文档

六、内置函数(map、filter、reduce)

map

# map()函数接收两个参数,一个是函数,一个是Iterable。
# map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回。

"""
小练习
利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。
输入:['adam', 'LISA', 'barT'],输出:['Adam', 'Lisa', 'Bart']:
"""

def normaliza(name):
    name = name.title()
    return name

l1 = ['adam', 'LISA', 'barT']
l2 = list(map(normaliza, l1))
print(l2)

# 更Pythonic的方法
l3 = list(map(str.title, l1))
print(l3)

output:

['Adam', 'Lisa', 'Bart']
['Adam', 'Lisa', 'Bart']

filter

# filter的练习,找出列表中大于50的元素

l1 = [12, 33, 54, 6, 48, 98]
l2 = list(filter(lambda t: t > 50, l1))
print(l2)

output:

[54, 98]

reduce:

reduce在3.0移到了functools模块

from functools import reduce

"""
Python提供的sum()函数可以接受一个list并求和,请编写一个prod()函数,可以接受一个list并利用reduce()求积
"""

def prod(l):
    return reduce(lambda x, y: x * y, l)

print('3*5*7*9=', prod([3, 5, 7, 9]))

output:

3*5*7*9= 945

补充练习:

from functools import reduce

"""
利用map和reduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456
"""

def str2float(s):
    m = s.split('.')
    i1 = list(map(int, m[0]))
    i2 = list(map(int, m[1]))
    i2.reverse()
    f1 = reduce(lambda x, y: x*10+y, i1)
    f2 = reduce(lambda x, y: x*0.1+y, i2)
    return f1+f2/10

print('字符串转换成浮点数=>', str2float('123.456'))
print('字符串转换成浮点数=>', str2float('654.321'))

output:

字符串转换成浮点数=> 123.456
字符串转换成浮点数=> 654.321

Python之路Day3的更多相关文章

  1. Python之路,Day3 - Python基础3

    一.文件操作 对文件操作流程 打开文件,得到文件句柄并赋值给一个变量 通过句柄对文件进行操作 关闭文件 现有文件如下 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ...

  2. Python之路 day3 高阶函数

    #!/usr/bin/env python # -*- coding:utf-8 -*- #Author:ersa """ 变量可以指向函数,函数的参数能接收变量, 那么 ...

  3. Python之路 day3 递归函数

    #!/usr/bin/env python # -*- coding:utf-8 -*- #Author:ersa """ 在函数内部,可以调用其他函数.如果一个函数在内 ...

  4. Python之路 day3 全局变量、局部变量

    #!/usr/bin/env python # -*- coding:utf-8 -*- #Author:ersa """ 全局与局部变量 在子程序中定义的变量称为局部变 ...

  5. Python之路 day3 函数定义 *args及**kwargs

    #!/usr/bin/env python # -*- coding:utf-8 -*- #Author:ersa import time # def logger(): # time_format ...

  6. python之路-Day3

    字典 dic{key:value} 元组与列表相似,唯一就是不能修改dic = {'name':'alex','age':18}查询print(dic['name']) #会报错get方法查询,查询之 ...

  7. 小白的Python之路 day3 函数式编程,高阶函数

    函数式编程介绍   函数是Python内建支持的一种封装,我们通过把大段代码拆成函数,通过一层一层的函数调用,就可以把复杂任务分解成简单的任务,这种分解可以称之为面向过程的程序设计.函数就是面向过程的 ...

  8. 小白的Python之路 day3 函数

    1.函数基本语法及特性 背景提要 现在老板让你写一个监控程序,监控服务器的系统状况,当cpu\memory\disk等指标的使用量超过阀值时即发邮件报警,你掏空了所有的知识量,写出了以下代码 1 2 ...

  9. Python之路

    Python学习之路 第一天   Python之路,Day1 - Python基础1介绍.基本语法.流程控制              第一天作业第二天   Python之路,Day2 - Pytho ...

随机推荐

  1. 《TCP/IP详细说明》读书笔记(17章)-TCP传输控制协定

    1.TCP的服务 在一个TCP连接中.仅有双方进行彼此通信. TCP通过下列方式来提供可靠性: 1)应用数据被切割成TCP觉得最适合发送的数据块. 这和UDP全然不同,应用程序产生的数据报长度保持不变 ...

  2. java Script 中的keyCode 和charCode

    其实很长一段时间,我都没有完全弄明白keyCode 和charCode ,自己也认真看过,但是就是理解不透彻,为了防止以后再出现混乱,写篇博客记录一下吧! 首先  在不同的浏览器中,他们有不同的说法哦 ...

  3. BZOJ 1600: [Usaco2008 Oct]建造栅栏( dp )

    QAQ我没读过书...四边形都不会判定了 简单的dp.... --------------------------------------------------------------------- ...

  4. win64位 apache2.4 php5.4 mysql5.6

    apache2.4 php5.4 mysql5.6 源文件下载 +以前的配置数据参考 链接:http://pan.baidu.com/s/1skfmGyT 密码:hqtp 比较好的参考资料 http: ...

  5. js,this,constrct ,prototype

    这一章我们将会重点介绍JavaScript中几个重要的属性(this.constructor.prototype), 这些属性对于我们理解如何实现JavaScript中的类和继承起着至关重要的作 th ...

  6. 安装CDH

    Cloudera Manager 4.8.2 http://www.idefs.com/recordsubuntu-12-04-cloudera-installation-manager-4-8-2- ...

  7. JFreeChart画折线图

    请见Github博客: http://wuxichen.github.io/Myblog/htmlcss/2014/09/01/JFreechartLinechart.html

  8. C 语言统计关键字出现次数

    #include <stdio.h> #include <ctype.h> #include <string.h> #define NKEYS (sizeof ke ...

  9. Wiki: HSL和HSV色彩空间

    HSL 和 HSV(也叫做 HSB)是对RGB 色彩空间中点的两种有关系的表示,它们尝试描述比 RGB 更准确的感知颜色联系,并仍保持在计算上简单.HSL 表示 hue(色相).saturation( ...

  10. [ArcGIS必打补丁]ArcGIS 10.1 SP1 for (Desktop, Engine, Server) Quality Improvement Patch

    大家都知道假设希望保证企业级GIS系统的稳定执行,除了使用最新的ArcGIS版本号产品以外,还须要打上相关的补丁. 补丁分为:Service Pack和Patch 比如,假设你使用的ArcGIS10. ...