摘要:

复习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. [Asp.net]常见word,excel,ppt,pdf在线预览方案(转)

    引言 之前项目需要,查找了office文档在线预览的解决方案,顺便记录一下,方便以后查询. 方案一 直接在浏览器中打开Office文档在页面上的链接.会弹出如下窗口: 优点:主流浏览器都支持. 缺点: ...

  2. 安卓入门学习之Hello,world!

    第二章 Hello,world! 本文同时发表至简书,不为什么,用他的MarkDown在线编辑爽得要哭. 注意:本章节所使用的开发工具为Eclipse 以Android编程权威指南作为学习书物 第一节 ...

  3. CSS的display、hover、overflow、&copy(版权符号)、borer-radius(边框圆角)

    一.display: none 隐藏 block显示     visibility:hidden隐藏 visible显示 display:none和visibility:hidden这两个属性对应的值 ...

  4. 关于hibernate子查询参数的问题

    private Map<String, Object> createWblHqlContext(boolean needGroup, String startDate, String en ...

  5. 在myeclipse中修改svn帐户

    把C:\Users\Administrator\AppData\Roaming\Subversion\auth\这个文件中所有文件删除 然后在myeclipse中同步会让你输入用户名和密码

  6. python成长之路15

    一:JavaScript: JavaScript是一门编程语言,浏览器内置了JavaScript语言的解释器,所以在浏览器上按照JavaScript语言的规则编写相应代码之,浏览器可以解释并做出相应的 ...

  7. [LeetCode]题解(python):012-Integer to Roman

    题目来源: https://leetcode.com/problems/integer-to-roman/ 题意分析: 这道题是要把在区间[1-3999]的数字转化成罗马数字. 题目思路: 只要知道了 ...

  8. FPGA知识大梳理(三)verilogHDL语法入门(2)知识汇总

    1,时序逻辑.将上次的练习修改成时序逻辑会如何设计. always @ (posedge clock) 2,block 与unblocking  A,有clock的always中通常使用nonbloc ...

  9. 顺为资本CEO许达来:为什么说中国创业者很幸福?(附PPT)

    顺为资本创始合伙人许达来 编者按:许达来,顺为资本创始合伙人及CEO,代表性投资项目包括小米科技.丁香园.一起作业.加一联创.金山软件及兴达国际等. 本文为许达来在新浪创业举办的新创课活动上的内容分享 ...

  10. python:利用asyncio进行快速抓取

    web数据抓取是一个经常在python的讨论中出现的主题.有很多方法可以用来进行web数据抓取,然而其中好像并没有一个最好的办法.有一些如scrapy这样十分成熟的框架,更多的则是像mechanize ...