码迷,mamicode.com
首页 > 编程语言 > 详细

Python 3.5学习笔记(第二周)

时间:2018-04-15 12:07:21      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:div   内置模块   官网   for   www.   扩展   用法   get   识别   

声明:本文只用作记录自己的学习过程,请勿用于商业用途,部分内容引用自他人文章,如有侵权,联系删除。

本周内容

  1、模块

  2、数据类型与数据运算

  3、进制

  4、byte 与 string 的互相转换

  5、列表

  6、元组

  7、字符串操作

  8、字典

 

一、模块

  Python 把某些常用的定义存放在文件中,为一些脚本或者交互式的解释器实例使用,这个文件被称为模块。模块是一个包含所有你定义的函数和变量的文件,其后缀名是.py。模块可以被别的程序引入,以使用该模块中的函数等功能。Python中有两种模块,一种是内置模块,也称为标准库,另一种是自定义模块,称为第三方库

1、标准库

  标准库无需独立安装,可以直接使用。比如sys模块和os模块。

1 import sys
2 print(sys.path,"\n")
3 print(sys.argv)

 

1 import os
2 cmd_com = os.system("dir")
3 print(cmd_com)

 

1 import os
2 os.mkdir("new_dir")
#创建新目录

 

2、第三方库

  在Python中,安装第三方模块,是通过setuptools这个工具完成的。Python有两个封装了setuptools的包管理工具:easy_installpip。目前官方推荐使用pip。在命令提示符窗口下尝试运行pip,现在,让我们来安装一个第三方库——Python Imaging Library,这是Python下非常强大的处理图像的工具库。一般来说,第三方库都会在Python官方的pypi.python.org网站注册,要安装一个第三方库,必须先知道该库的名称,可以在官网或者pypi上搜索,比如Python Imaging Library的名称叫PIL,因此,安装Python Imaging Library的命令就是:

1 pip install PIL

  模块的调用:

  模块在调用时,会首先从当前文件目录下寻找模块,可以将模块直接放到python安装文件的site-package 目录下直接放在当前文件夹中,这样就可以直接调用。

1 import login

  或者在当前目录下创建一个文件夹用于放置模块,命名为module,将需要的模块放在module文件夹下,同时在该文件夹下创建 _init_.py 文件用于表示该文件夹是一个模块库。

  需要调用module模块库中的login 模块,可以用下面的方法:

1 import module.login

  或者

1 from module import login

  当导入的模块中有多个函数,比如 login 中分别定义了 func_1 和 func_2 ,就可以用下面的方法分别调用对应的函数

1 from module import login
2 login.func_1()
3 login.func_2()

  如果模块名过长,比如TemperatureConversion.py ,每次都要调用很麻烦,可以使用下面的方法简化调用过程

1 from module import TemperatureConversion as tc
2 tc.fun_1()
3 tc.fun_2()

  示例:通过PIL模块库中Image 模块读取并显示图片

1 from PIL import  Image
2 im = Image.open("图片.png")
3 im.show()

 

  补充:pyc文件

  pyc是一种二进制文件,是由py文件经过编译后,生成的文件,是一种byte code,py文件变成pyc文件后,加载的速度有所提高,而且pyc是一种跨平台的字节码,是由python的虚拟机来执行的,这个是类似于JAVA或者.NET的虚拟机的概念。pyc的内容,是跟python的版本相关的,不同版本编译后的pyc文件是不同的。

 

二、数据类型与数据运算

  1、python支持四种不同的数据类型 int整型、bool布尔型、float浮点型、complex复数

1 var1 = 10; #表示整型
2 var2 = True #表示布尔型
3 var3 = 12.34;#表示浮点型
4 var4 = 123j #复数
5 var5 = 123+45j #复数

  2、科学记数法:用  E(e) 表示 10的次方 。

  3、基础运算

  (1)加: +

1 1 + 1

  (2)减: -

1 1 - 1

  (3)乘: *

1 1 * 1

  (4)除:

      普通除法:   /

1 9 / 2

      地板除:     //    (结果只取整数部分)

1 9 // 2

              取余数:    %

1 9 // 2

  (5)幂运算: ** 

1 2 ** 3

 

三、进制

  常用转换表如下:

二进制 八进制 十进制 十六进制
0000 0 0 0
0001 1 1 1
0010 2 2 2
0011 3 3 3
0100 4 4 4
0101 5 5 5
0110 6 6 6
0111 7 7 7
1000 10 8 8
1001 11 9 9
1010 12 10 A
1011 13 11 B
1100 14 12 C
1101 15 13 D
1110 16 14 E
1111 17 15 F

  

  表示方法: 0开始表示8进制,0x开始表示16进制

  具体转换方法见链接: 

    https://jingyan.baidu.com/article/495ba84109665338b30ede98.html

 

四、byte 与 string 的互相转换 

  1、bytes主要是给在计算机看的,string主要是给人看的

  2、中间有个桥梁就是编码规则,现在大趋势是utf8

  3、bytes对象是二进制,很容易转换成16进制,例如\x64

  4、string就是我们看到的内容,例如‘abc‘

  5、string经过编码encode,转化成二进制对象,给计算机识别

  6、bytes经过反编码decode,转化成string,让我们看,但是注意反编码的编码规则是有范围,\xc8就不是utf8识别的范围

 

五、列表

1、列表的创建

1 names = ["","","","","","","",""]
2 print(names)
>>>[‘赵‘, ‘钱‘, ‘孙‘, ‘李‘, ‘周‘, ‘吴‘, ‘郑‘, ‘王‘]

2、通过下标取出列表中的元素

(1)取出列表中的第一个元素

1 names = ["","","","","","","",""]
2 print(names[0])
>>>赵
#列表的下标是从 0 开始计算的。

(2)取出列表中的最后一个元素

1 names = ["","","","","","","",""]
2 print(names[-1])
>>>王

3、列表的切片

(1)取出前三个元素

1 names = ["","","","","","","",""]
2 print(names[0:3])
>>>[‘赵‘, ‘钱‘, ‘孙‘]
#[ a : b ] 不包含b,且a 不能大于b,如果a为0,或者b为最后一个元素的下标,都可以省略。

(2)取出最后两个元素

1 names = ["","","","","","","",""]
2 print(names[-2:])
>>>[‘郑‘, ‘王‘]

4、向列表中追加元素

1 names = ["","","","","","","",""]
2 names.append("")
3 print(names)
>>>[‘赵‘, ‘钱‘, ‘孙‘, ‘李‘, ‘周‘, ‘吴‘, ‘郑‘, ‘王‘, ‘冯‘]
#默认追加到列表的最后一位

5、向指定位置插入元素

1 names = ["","","","","","","",""]
2 names.insert(2,"")
3 print(names)
>>>[‘赵‘, ‘钱‘, ‘冯‘, ‘孙‘, ‘李‘, ‘周‘, ‘吴‘, ‘郑‘, ‘王‘]
#insert()包含两个参数,第一个参数是指定插入的位置,第二个参数是插入的元素

6、更改指定的元素

1 names = ["","","","","","","",""]
2 names[2] = ""
3 print(names)
>>>[‘赵‘, ‘钱‘, ‘蒋‘, ‘李‘, ‘周‘, ‘吴‘, ‘郑‘, ‘王‘]

7、删除指定的元素

(1)remove()

1 names = ["","","","","","","",""]
2 names.remove("")
3 print(names)
>>>[‘赵‘, ‘钱‘, ‘孙‘, ‘周‘, ‘吴‘, ‘郑‘, ‘王‘]

(2)del 

1 names = ["","","","","","","",""]
2 del names[2]
3 print(names)
>>>[‘赵‘, ‘钱‘, ‘李‘, ‘周‘, ‘吴‘, ‘郑‘, ‘王‘]

(3)pop()

1 names = ["","","","","","","",""]
2 names.pop(5)
3 print(names)
>>>[‘赵‘, ‘钱‘, ‘孙‘, ‘李‘, ‘周‘, ‘郑‘, ‘王‘]
# pop() 需要一个参数,当不指定参数时,默认删除最后一个元素

8、查找元素的位置

1 names = ["","","","","","","",""]
2 print(names.index(""))
>>>2
#默认返回从0起第一个指定参数的位置

 9、统计某一个元素出现的次数

1 names = ["","","","","","","",""]
2 print(names.count(""))
>>>1

10、清空列表

1 names = ["","","","","","","",""]
2 names.clear()
3 print (names)
>>>[]

11、将列表翻转

1 names = ["","","","","","","",""]
2 names.reverse()
3 print (names)
>>>[‘王‘, ‘郑‘, ‘吴‘, ‘周‘, ‘李‘, ‘孙‘, ‘钱‘, ‘赵‘]

12、将列表中的元素按ASCII码排序

1 names = ["","","","","","","",""]
2 names.sort()
3 print (names)
>>>[‘吴‘, ‘周‘, ‘孙‘, ‘李‘, ‘王‘, ‘赵‘, ‘郑‘, ‘钱‘]

13、用一个列表来扩展原列表

1 names = ["","","","","","","",""]
2 names_2 = ["","","","","","","","",]
3 names.extend(names_2)
4 print (names)
>>>[‘赵‘, ‘钱‘, ‘孙‘, ‘李‘, ‘周‘, ‘吴‘, ‘郑‘, ‘王‘, ‘冯‘, ‘陈‘, ‘褚‘, ‘卫‘, ‘蒋‘, ‘沈‘, ‘韩‘, ‘杨‘]

14、计算列表中元素的总个数

1 names = ["","","","","","","",""]
2 print (len(names))
>>>8

15、复制列表

(1)浅复制

1 names = ["","","","","","","",""]
2 names_2 = names.copy()
3 print (names_2)
>>>[‘赵‘, ‘钱‘, ‘孙‘, ‘李‘, ‘周‘, ‘吴‘, ‘郑‘, ‘王‘]

  浅复制只复制列表的第一层,并且第一层是互相独立的,修改其中任何一个列表,另外的列表都不会受到影响。

1 names = ["","","","","","","",""]
2 names_2 = names.copy()
3 names_2[0] = ""
4 names[6] = ""
5 print(names)
6 print (names_2)
>>>

[‘赵‘, ‘钱‘, ‘孙‘, ‘李‘, ‘周‘, ‘吴‘, ‘陈‘, ‘王‘]
[‘杨‘, ‘钱‘, ‘孙‘, ‘李‘, ‘周‘, ‘吴‘, ‘郑‘, ‘王‘]

  但是如果列表中还嵌套着下一级列表,则浅复制之后的第二级及以上的列表如果被修改,其他的列表都会跟着改变,因为第二级复制的只是内存地址,当修改了第二级列表,实际上是修改了内存中的值。

1 names = ["","","","","","","","",["","","",""]]
2 names_2 = names.copy()
3 names_2[8][2] = ""
4 names[8][3] = ""
5 print(names)
6 print (names_2)
>>>

[‘赵‘, ‘钱‘, ‘孙‘, ‘李‘, ‘周‘, ‘吴‘, ‘郑‘, ‘王‘, [‘冯‘, ‘陈‘, ‘杨‘, ‘韩‘]]
[‘赵‘, ‘钱‘, ‘孙‘, ‘李‘, ‘周‘, ‘吴‘, ‘郑‘, ‘王‘, [‘冯‘, ‘陈‘, ‘杨‘, ‘韩‘]]

16、列表的嵌套

1 names = ["","","","","","","",""]
2 names_2 = ["","","","","","","",""]
3 names[7] = names_2
4 print(names)
5 print(names[7][5])

>>>[‘赵‘, ‘钱‘, ‘孙‘, ‘李‘, ‘周‘, ‘吴‘, ‘郑‘, [‘冯‘, ‘陈‘, ‘褚‘, ‘卫‘, ‘蒋‘, ‘沈‘, ‘韩‘, ‘杨‘]]

 17、列表的循环

(1)普通循环

1 names = ["","","","","","","",""]
2 for each in names:
3     print(each,end =  )
>>>赵 钱 孙 李 周 吴 郑 王 
#end = " " 表示每一次打印完姓氏之后,以end 指定的内容结尾,比如这里就是以空格结尾,如果不加end = " ... " ,则默认是换行

(2)切片循环

1 names = ["","","","","","","",""]
2 for i in names[0:-1:2]:
3     print(i,end = "")
>>>赵孙周郑

 

六、元组

  元组实际上是一个不可以修改的列表,也称作只读列表,它只有两种用法:

(1)count()

1 name = ("","","","","","","","","","","")
2 print(name.count(""))
>>>2

(2)  index()

1 name = ("","","","","","","","","","","")
2 print(name.index(""))
>>>3
#默认返回从0起第一个指定参数的位置

 

七、字符串操作

1、首字母大写

1 strings = "i love you"
2 print(strings.capitalize())
>>>I love you
#只把第一个字母大写

2、统计字符串中字符的个数

1 strings = "i love you"
2 print(strings.count("o"))
>>>2

3、字符串补齐

(1)两侧补齐

1 strings = "i love you"
2 print(strings.center(50,"-"))
>>>--------------------i love you--------------------
#一共打印50个字符,将strings放在中间,两边用”-“补齐

(2)左侧补齐

1 strings = "I Love You"
2 print(strings.rjust(20,"-"))
>>>----------I Love You

(3)右侧补齐

1 strings = "I Love You"
2 print(strings.ljust(20,"-"))
>>>I Love You----------

4、字符串转换为二进制编码

1 strings = "i love you"
2 print(strings.encode())
>>>b‘i love you‘

5、判断字符串是否以指定字符结尾

1 strings = "i love you"
2 print(strings.endswith("you"))
>>>True

6、查找字符串中指定字符的第一个索引

1 strings = "i love you"
2 print(strings.find("o"))
>>>3

7、字符串切片

1 strings = "i love you"
2 print(strings[0:6])
>>>i love

8、字符串格式化

1 strings = "{a} love {b}"
2 print(strings.format(a = you , b = "i"))
>>>you love i


9、用字典进行格式化

1 strings = "{a} love {b}"
2 print(strings.format_map({"a":"you","b":"i"}))
>>>you love i

10、查找元素的索引

1 strings = "i love you"
2 print(strings.index("o"))
>>>3
#默认显示从0开始第一个指定元素的索引

11、判断字符串是否是阿拉伯数字或者英文字母组成

1 strings = "i love you 1314"
2 print(strings.isalnum())
>>>False
1 strings = "iloveyou1314"
2 print(strings.isalnum())
>>>True

12、判断字符串是否为纯英文组成

1 strings = "iloveyou"
2 print(strings.isalpha())
>>>True
#只能是英文字母,不能有数字,空格等

13、判断字符串是否为十进制

1 strings = "1314"
2 print(strings.isdecimal())
>>>True

14、判断字符串是否为整数

1 strings = "1314"
2 print(strings.isdigit())、
>>>True

15、判断字符串是否为合法的标识符(变量名)

1 strings = "MR1314"
2 print(strings.isidentifier())
>>>True

16、判断字符串为否为全部小写

1 strings = "i love you"
2 print(strings.islower())
>>>True

17、判断字符串为否为全部大写

1 strings = "I LOVE YOU"
2 print(strings.isupper())
>>>True

18、判断字符串是否为纯数字(不包括小数)

1 strings = "1423154361"
2 print(strings.isnumeric())
>>>True

19、判断字符串是否为标题格式

1 strings = "I Love You"
2 print(strings.istitle())
>>>True

20、把字符串重复插入另一个字符串的每两个字符中间

1 strings = "+"
2 print(strings.join("123"))
>>>1+2+3

21、大小写单向转换

(1)大写转换为小写

1 strings = "I Love You"
2 print(strings.lower())
>>>i love you

(2)小写转化为大写

1 strings = "I Love You"
2 print(strings.upper())
>>>I LOVE YOU

22、去除字符串外面的空格

(1)去除两端的空格

1 strings = "   I Love You    "
2 print(strings.strip())
>>>I Love You

(2)去除左侧的空格

1 strings = "   I Love You    "
2 print(strings.lstrip())
>>>I Love You    

(3)去除右侧的空格

1 strings = "   I Love You    "
2 print(strings.rstrip())
>>>   I Love You

23、根据指定转换关系表对字符串进行转换

1 strings = "abcdefghijklmn"
2 p = str.maketrans("abcdefg","1234567")
3 print(strings.translate(p))
>>>1234567hijklmn

24、字符串替换

1 strings = "abcdefghijklmn"
2 print(strings.replace(b,"B"))
>>>aBcdefghijklmn

25、字符串索引

(1)普通索引

1 strings = "abcdefghijklmbn"
2 print(strings.find(b))
>>>1

(2)从右侧开始索引

1 strings = "abcdefghijklmbn"
2 print(strings.rfind(b))
>>>13

26、字符串分割

(1)自定义分割

1 strings = "a b c d e fghi jklmbn"
2 print(strings.split(" "))
>>>[‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘fghi‘, ‘jklmbn‘]
#分割后的元素放入列表中

(2)换行符分割

1 strings = "a \n b c d e fghi jklmbn"
2 print(strings.splitlines())
>>>[‘a ‘, ‘ b c d e fghi jklmbn‘]

27、判断字符串是否以指定内容为开头

1 strings = "a b c d e fghi jklmbn"
2 print(strings.startswith("a"))
>>>True

28、大小写互换

1 strings = "aBcdEFSKHmbn"
2 print(strings.swapcase())
>>>AbCDefskhMBN

29、字符串标题化

1 strings = "i love you"
2 print(strings.title())
>>>I Love You

 

八、字典

1、字典的创建

1 capital = {"China":"BeiJing","America":"NewYork","England":"London","France":"Paris"}
2 print(capital)
>>>{‘America‘: ‘NewYork‘, ‘England‘: ‘London‘, ‘France‘: ‘Paris‘, ‘China‘: ‘BeiJing‘}
#字典是无序的,也没有下标

2、查找字典中的key对应的value

1 capital = {"China":"BeiJing","America":"NewYork","England":"London","France":"Paris"}
2 print(capital["China"])
>>>BeiJing

3、更改字典的key对应的value

1 capital = {"China":"BeiJing","America":"Washington","England":"London","France":"Paris"}
2 capital["America"] = "NewYork"
3 print(capital)
>>>{‘China‘: ‘BeiJing‘, ‘America‘: ‘NewYork‘, ‘France‘: ‘Paris‘, ‘England‘: ‘London‘}

4、在字典中添加新的key-value

1 capital = {"China":"BeiJing","America":"Washington","England":"London","France":"Paris"}
2 capital["Kerea"] = "Seoul"
3 print(capital)
>>>{‘China‘: ‘BeiJing‘, ‘France‘: ‘Paris‘, ‘Kerea‘: ‘Seoul‘, ‘America‘: ‘Washington‘, ‘England‘: ‘London‘}

5、删除字典中的某一个key-value

(1)del 

1 capital = {"China":"BeiJing","America":"Washington","England":"London","France":"Paris"}
2 del capital["France"]
3 print(capital)
>>>{‘England‘: ‘London‘, ‘China‘: ‘BeiJing‘, ‘America‘: ‘Washington‘}

(2)pop()

1 capital = {"China":"BeiJing","America":"Washington","England":"London","France":"Paris"}
2 capital.pop("France")
3 print(capital)
>>>{‘China‘: ‘BeiJing‘, ‘America‘: ‘Washington‘, ‘England‘: ‘London‘}
#与列表中的pop不同,由于字典是无序的,所以字典在使用pop时必须指定参数

(3) popitem()

1 capital = {"China":"BeiJing","America":"Washington","England":"London","France":"Paris"}
2 capital.popitem()
3 print(capital)
>>>{‘China‘: ‘BeiJing‘, ‘America‘: ‘Washington‘, ‘England‘: ‘London‘}
#popitem()是随机删除字典中的key-value

6、查找字典中的key

1 capital = {"China":"BeiJing","America":"Washington","England":"London","France":"Paris"}
2 print(capital.get("Kerea"))
>>>None
#当查找的key不存在时返回None,不会报错
1 capital = {"China":"BeiJing","America":"Washington","England":"London","France":"Paris"}
2 print(capital.get("China"))
>>>BeiJing

7、多级字典的嵌套及操作

(1)修改二级字典中的value

1 district ={
2     "JiangSu":{"Nanjing":["LiuHe","PuKou"]},
3     "AnHui":{"HeFei":["YaoHai","BaoHe"]},
4     "HuBei":{"WuHan":["HongShan","WuChang"]}
5 }
6 district["HuBei"]["WuHan"][0] = "HanKou"
7 print(district)
>>>{‘HuBei‘: {‘WuHan‘: [‘HanKou‘, ‘WuChang‘]}, ‘JiangSu‘: {‘Nanjing‘: [‘LiuHe‘, ‘PuKou‘]}, ‘AnHui‘: {‘HeFei‘: [‘YaoHai‘, ‘BaoHe‘]}}

8、设置字典的默认值

1 capital = {"China":"BeiJing","America":"Washington","England":"London","France":"Paris"}
2 capital.setdefault("America","Soule")
3 print(capital)
>>>{‘England‘: ‘London‘, ‘France‘: ‘Paris‘, ‘America‘: ‘Washington‘, ‘China‘: ‘BeiJing‘}
#寻找字典中的key,已存在则更改相应的value,不存在则添加新的key-value

9、更新字典

1 capital = {"China":"BeiJing","America":"Washington","England":"London","France":"Paris"}
2 capital2 = {"China":"BeiJing","America":"Moscow","England":"London","France":"Paris","Kerea":"Soule"}
3 capital.update(capital2)
4 print(capital)
>>>{‘France‘: ‘Paris‘, ‘England‘: ‘London‘, ‘China‘: ‘BeiJing‘, ‘America‘: ‘Moscow‘, ‘Kerea‘: ‘Soule‘}
#用字典capital2 来更新capital,有交叉则覆盖,多余的就新添加进去

10、将字典转换为由元组组成的列表

1 capital = {"China":"BeiJing","America":"Washington","England":"London","France":"Paris"}
2 print(capital.items())
3 for key,value in capital.items():
4     print (key,value)
>>>

dict_items([(‘America‘, ‘Washington‘), (‘China‘, ‘BeiJing‘), (‘England‘, ‘London‘), (‘France‘, ‘Paris‘)])
America Washington
China BeiJing
England London
France Paris

11、创建一个不同key 对应相同 value 的字典

1 capital= dict.fromkeys([1,2,3],"Amazing")
2 print(capital)
>>>{1: ‘Amazing‘, 2: ‘Amazing‘, 3: ‘Amazing‘}
#无论value是多少,是字符串还是列表,都被组合成一个值,对应不同的key,如果修改其中一个的value,其他的value都会跟着更改。

12、字典的循环

1 capital = {"China":"BeiJing","America":"Washington","England":"London","France":"Paris"}
2 for i in capital:
3     print(i,":",capital[i])
>>>

China : BeiJing
America : Washington
France : Paris
England : London

 

Python 3.5学习笔记(第二周)

标签:div   内置模块   官网   for   www.   扩展   用法   get   识别   

原文地址:https://www.cnblogs.com/muouran0120/p/8824206.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!