写在前面
大人不华,君子务实。
一、进制相关
- 进制基础
数据存储在磁盘上或者内存中,都是以0、1形式存在的;即是以 二进制 的形式存在;
为了存储和展示,人们陆续扩展了数据的表示形式:八进制 -> 十进制 -> 十六进制...
二进制: ...
八进制: ...
十进制: ...
十六进制: a b c d e f ...
- 文件读写相关函数方法
虽然硬盘上存储形式都是简单的0和1,但是随着计算机科学的快速普及和发展,兼容了越来越多的语言和文字;所以出现了很多编码形式;
然而每一种编码都有自己的对应关系且每个byte由8个bit组成:ASCII码规定每个字符由8个bit表示,不能表示汉字;utf-8规定每个汉字由24个bit表示;
更多参见:Python基础-day01
所以针对存储在硬盘上的数据,要想正确的识别并展示出来,就必须要知道其存储的编码格式,否则则会出现乱码;
#1 Python中文件读写的小例子:
1 #!/usr/bin/python
2 # -*- coding:utf-8 -*-
3
4 f1 = open('log','r',encoding='utf-8')
5 f2 = open('log','rb')
6 data1 = f1.read()
7 data2= f2.read()
8 print(data1)
9 print(data2)
10
11 result:
12 D:\soft\work\python35\python.exe D:/soft/work/Python_17/day02/s01.py
13 adada英文——_.
14 b'adada\xe8\x8b\xb1\xe6\x96\x87\xe2\x80\x94\xe2\x80\x94_.'
15
16 Process finished with exit code 0 log文件内容:adada英文——_.
二、类和对象初探
- 类/class
类,具有某些属性和行为的抽象结构;
代码中,属性对应了一些变量,行为则对应了一些具体的方法;
- 对象/object
对象,是类的实例,即具有某些属性和行为的实物;
- 面向对象
- 封装
- 继承
- 多态
- 重载
...
> 例如:水果是一个类/class,香蕉则是一个对象/object;
- Python 中的类和对象
比如我们常用的字符串类型:
class str(object):{...}
---
#!/usr/bin/python
# -*- coding:utf-8 -*- string = "Hello"
new_str = string.upper()
print(new_str)
string 变量通过 '=' 赋值,成为了一个str类的对象实例,存储在内存中;因为str类具有 'upper()' 方法,所以string对象继承了该方法,可以执行相关操作;
三、基本数据类型常用方法介绍
- 字符串/str
- 类型: 不可变(immutable)
下面这个小例子,试图修改字符串,解释器报错;
#!/usr/bin/python
# -*- coding:utf-8 -*- string = "Hello"
print(string)
print(string[2])
string[2] = '+'
print(string)
print(string[2]) ---
D:\soft\work\python35\python.exe D:/soft/work/Python_17/day02/s03.py
Hello
l
Traceback (most recent call last):
File "D:/soft/work/Python_17/day02/s03.py", line 9, in <module>
string[2] = '+'
TypeError: 'str' object does not support item assignment Process finished with exit code 1
- 基础功能
- 1.capitalize | 首字母大写
name = 'alex'
v = name.capitalize()
print(name)
print(v) ---
alex
Alex
- 2.casefold 和 lower | 所有大写变小写,casefold 功能强于 lower
name = 'HeLLo!'
v = name.casefold()
v2 = name.lower()
print(name)
print(v)
print(v2) ---
HeLLo!
hello!
hello!
# ß 是德语里的一个大写字符 name = 'ß'
v = name.casefold()
v2 = name.lower()
print(v)
print(v2) ---
ss
ß
- 3.center, ljust, rjust | 文本居中,居左,居右,并填充显示,arg1 -> 表示总长度;arg2 -> 表示填充字符;
name = 'standby'
v = name.center(10,'#')
v2 = name.ljust(10,'@')
v3 = name.rjust(10,'+')
print(v)
print(v2)
print(v3) ---
#standby##
standby@@@
+++standby
- 4.count | 子序列在字符串中出现的次数;arg1 -> 子序列; arg2 -> 匹配查找的起始位置; arg3 -> 匹配查找的结束位置;
desc = "This is www.iqiyi.com."
v = desc.count('i')
v2 = desc.count('is')
v3 = desc.count('is',1,5)
print(v)
print(v2)
print(v3) ---
5
2
1
- 5.encode | 把字符串转换成 bytes 类型表示; arg1 -> 指定编码;
name = '中国'
new_name1 = name.encode('utf-8')
new_name2 = name.encode('gbk')
print(new_name1, type(new_name1), len(new_name1))
print(new_name2, type(new_name2), len(new_name2)) ---
b'\xe4\xb8\xad\xe5\x9b\xbd' <class 'bytes'> 6
b'\xd6\xd0\xb9\xfa' <class 'bytes'> 4
- 6.endswith 和 startswith | 是否以xxx结尾、开头; arg1 -> xxx;arg2 -> 匹配查找的起始位置; arg3 -> 匹配查找的结束位置;
hitwh = "Just stick to what you love and believe in."
v = hitwh.startswith('Just')
v2 = hitwh.startswith('s',5,11)
v3 = hitwh.endswith('t',5,12)
print(v,v2,v3) ---
True True True
- 7.expandtabs | 找到制表符\t,进行替换;arg1 -> 指定替换后的长度(包含 '\t' 前面的子序列);
my = 'haha\tPython_17\twww.baidu.com\nwww.standby.pub\txxxx\tlike'
print(my)
v = my.expandtabs(20)
print(v) ---
haha Python_17 www.baidu.com
www.standby.pub xxxx like
haha Python_17 www.baidu.com
www.standby.pub xxxx like
- 8.find 和 index | 查找子序列索引位置,不存在则返回 '-1';index查找,不存在的话就报错了;默认是从左向右查找,另外还有 rfind 和 rindex,即从右向左查找;
name = 'alex'
v = name.find('e')
v2 = name.find('o')
print(v)
print(v2) ---
2
-1
name = 'alex'
v = name.index('o')
print(v) ---
Traceback (most recent call last):
File "D:/soft/work/Python_17/day02/s02.py", line 35, in <module>
v = name.index('o')
ValueError: substring not found
- 9.format 和 format_map | 格式化输出的几种形式
# Format output 1
my = "I am %s, age is %s, gender is %s."
print(my % ('standby',22,'male'))
# Format output 2
my = "I am {0}, age is {1}, gender is {2}."
print(my.format('standby',23,'male'))
# Format output 3
my = "I am {name}, age is {age}, gender is {gender}."
print(my.format(name = 'standby',age = 24,gender = 'male'))
# Format output 4
my = "I am {name}, age is {age}, gender is {gender}."
print(my.format_map({'name':'standby','age':25,'gender':'male'})) ---
I am standby, age is 22, gender is male.
I am standby, age is 23, gender is male.
I am standby, age is 24, gender is male.
I am standby, age is 25, gender is male.
- 10.isdecimal, isdigit, isnumeric | 判断是否是数字;isdecimal < isdigit < isnumeric
num = ''
num2 = '九十八'
num3 = '⑨'
v1 = num.isdecimal()
v2 = num.isdigit()
v3 = num.isnumeric()
print(v1,v2,v3)
v1 = num2.isdecimal()
v2 = num2.isdigit()
v3 = num2.isnumeric()
print(v1,v2,v3)
v1 = num3.isdecimal()
v2 = num3.isdigit()
v3 = num3.isnumeric()
print(v1,v2,v3) ---
True True True
False False True
False True True
- 11.isalpha | 判断字符串是否只有字母组成
string = 'str'
name = 'alex123'
v = name.isalpha()
v2 = string.isalpha()
print(v)
print(v2) ---
False
True
- 12.isalnum | 判断字符串是否由字母和数字组成
name = 'alex123'
string = 'str赢.'
v = name.isalnum()
v2 = string.isalnum()
print(v)
print(v2) ---
True
False
- 13.isidentifier | 判断是否可以用作标识符、变量名
string1 = '1a'
string2 = 'int'
string3 = 'name'
v = string1.isidentifier()
v2 = string2.isidentifier()
v3 = string3.isidentifier()
print(v)
print(v2)
print(v3) ---
False
True
True
- 14.islower 和 isupper | 判断字符串是否全都是大、小写
name = 'aLeX'
v = name.islower()
v2 = name.isupper()
print(v)
print(v2)
print(name.upper())
print(name.lower()) ---
False
False
ALEX
alex
- 15.isprintable | 是否包含隐含的 '\t' '\n' '\a'...
desc = 'aaa121212---.'
name = 'alex \tsss'
v = name.isprintable()
v2 = desc.isprintable()
print(v)
print(v2) ---
False
True
- 16.isspace | 是否全部是空格
name = ' '
name2 = ' .'
v = name.isspace()
v2 = name2.isspace()
print(v)
print(v2) ---
True
False
- 17.join | 字符串/子序列拼接
str = 'alexall'
list = ['A','L','E','X']
v = '-'.join(str)
v2 = ''.join(list)
v3 = '<-->'.join(list)
print(v)
print(type(v2),v2)
print(type(v3),v3) ---
a-l-e-x-a-l-l
<class 'str'> ALEX
<class 'str'> A<-->L<-->E<-->X
- 18.lower, upper, swapcase | 大小写转换:全部变小写、全部变大写、大小写全部对换
name = 'AleX'
v = name.lower()
v2 = name.upper()
v3 = name.swapcase()
print(v)
print(v2)
print(v3) ---
alex
ALEX
aLEx
- 19.strip, rstrip, lstrip | 移除空白,'\n','\t',也可以自定义要移除的字符
name2 = ' standby '
v2 = name2.strip()
v3 = name2.lstrip()
v4 = name2.rstrip()
print(v2)
print(v3)
print(v4) ---
standby
standby
standby
name = 'alex'
v = name.strip("x")
v2 = name.strip("a")
print(v)
print(v2) ---
ale
lex
- 20.maketrans 和 translate | 对应关系 + 翻译
m = str.maketrans('hello','') # 对应关系
name = "---->hello@world<-----"
v = name.translate(m)
print(v) ---
---->12445@w5r4d<-----
- 21.partition,rpartition | 分割字符串,并保留自定义的分隔符;arg1 -> 分隔符;则返回一个3元的元组,第一个为分隔符左边的子串,第二个为分隔符本身,第三个为分隔符右边的子串。
name = 'standby'
v = name.partition('nd')
print(type(v),v)
v1 = name.split('nd')
print(type(v1),v1) ---
<class 'tuple'> ('sta', 'nd', 'by') <-- 元组,并且保留了自定义的分隔符: nd
<class 'list'> ['sta', 'by'] <-- 列表,去掉了自定义的分隔符
name = 'standby--nd++'
v = name.partition('nd')
v2 = name.rpartition('nd')
print(type(v),v)
print(type(v2),v2) ---
<class 'tuple'> ('sta', 'nd', 'by--nd++')
<class 'tuple'> ('standby--', 'nd', '++')
- 22.replace | 替换; arg1 -> 匹配的子序列; arg2 -> 指定替换后的子序列; arg3 -> 替换的个数
content = "巴基斯坦help中国help俄罗斯help中国"
print(content)
v = content.replace('help','Love')
print(v)
v = content.replace('help','Love',2)
print(v) ---
巴基斯坦help中国help俄罗斯help中国
巴基斯坦Love中国Love俄罗斯Love中国
巴基斯坦Love中国Love俄罗斯help中国
- 23.split, rsplit | 通过指定分隔符 arg1 对字符串进行切片,如果参数 arg2 有指定值,则仅分隔 arg2 个子序列
name = 'standby--nd++And######worldnd@@@.'
v = name.split('nd')
v2 = name.rsplit('nd')
v3 = name.split('nd',2)
v4 = name.rsplit('nd',2)
print(type(v),v)
print(type(v2),v2)
print(type(v3),v3)
print(type(v4),v4) ---
<class 'list'> ['sta', 'by--', '++A', '######world', '@@@.']
<class 'list'> ['sta', 'by--', '++A', '######world', '@@@.']
<class 'list'> ['sta', 'by--', '++And######worldnd@@@.']
<class 'list'> ['standby--nd++A', '######world', '@@@.']
- 24. zfill | 填充0; arg1 -> 指定总长度,包括已有字符串长度;
name = "alex"
v = name.zfill(10)
print(v) ---
000000alex
- 扩展补充
- 切片
desc = 'Hello @_@ world.'
print(desc)
print(desc[0])
print(desc[3:7])
print(desc[0:8:2]) ---
Hello @_@ world.
H
lo @
Hlo@
- 求长度和 for循环遍历
desc = 'Hello @_@ world.'
print(len(desc))
for i in desc:
print(i)
for i in range(0, len(desc)):
print(desc[i])
- 整数/int
- 类型 不可变(immutable)
>>> num=1
>>> id(num) <-- 查看num的内存地址
1795490256
>>> num2=1 <-- 给num2赋予同样的值:1
>>> id(num2) <-- num2 和 num 引用的是同一个内存地址,可见 Python3 在内存中为每一个值只保存一份;
1795490256
>>>
>>> num=9 <-- 给num重新赋值:9
>>> id(num) <-- num 的内存地址已经更改了,所以int值是不可变类型的!
1795490512
>>> id(num2)
1795490256
>>>
>>> num
9
>>> num2
1
>>>
- 基础功能
- 1.bit_length | 查看某整数用二进制表示时的最小位数; 可以用 'bin()' 函数获得整数的二进制表示形式;
print("十进制".ljust(5),"二进制".ljust(5), "二进制表示的最小位数")
for i in range(1,9):
print(str(i).ljust(10), bin(i).ljust(10), i.bit_length()) ---
十进制 二进制 二进制表示的最小位数
1 0b1 1
2 0b10 2
3 0b11 2
4 0b100 3
5 0b101 3
6 0b110 3
7 0b111 3
8 0b1000 4
- 2.to_bytes | 获取指定整数的字节按照大小端序进行表示
num_list = [254,255,256,257]
for age in num_list:
print("%s 大端序 --> %s" % (age, age.to_bytes(4,'big')))
print("%s 小端序 --> %s" % (age, age.to_bytes(4,'little'))) ---
254 大端序 --> b'\x00\x00\x00\xfe'
254 小端序 --> b'\xfe\x00\x00\x00'
255 大端序 --> b'\x00\x00\x00\xff'
255 小端序 --> b'\xff\x00\x00\x00'
256 大端序 --> b'\x00\x00\x01\x00'
256 小端序 --> b'\x00\x01\x00\x00'
257 大端序 --> b'\x00\x00\x01\x01'
257 小端序 --> b'\x01\x01\x00\x00'
- 3.from_bytes | 把指定大小端序的bytes对象转换成十进制整数表示
num_byte_list = [b'\x00\x00\x00\xfe', b'\x00\x00\x00\xff', b'\x00\x00\x01\x00', b'\x00\x00\x01\x01']
for by in num_byte_list:
print("%s 大端序转换为十进制数 --> %d" % (by, int.from_bytes(by, 'big'))) ---
b'\x00\x00\x00\xfe' 大端序转换为十进制数 --> 254
b'\x00\x00\x00\xff' 大端序转换为十进制数 --> 255
b'\x00\x00\x01\x00' 大端序转换为十进制数 --> 256
b'\x00\x00\x01\x01' 大端序转换为十进制数 --> 257
- 布尔值/bool
- 类型 不可变(immutable)
- 基础功能
- 1.整数里只有0是 False,其他都是 True
- 2.字符串里只有 "" 是 False,其他均是 True
- 3.如果列表为空,即[] 视为 False,其他均是 True
- 扩展补充
- 经常会把 'while True' 这样用作最外层的循环使用;
- 列表/list
- 类型 可变类型
-基础功能
- 1.append | 追加元素到列表
user_list = ['alex','eric','jerry','tim','alven']
v = user_list.append('beric')
print(v)
print(user_list) ---
None
['alex', 'eric', 'jerry', 'tim', 'alven', 'beric']
- 2.clear | 清空列表元素
user_list = ['alex','eric','jerry','tim','alven']
user_list.clear()
print(user_list) ---
[]
- 3.copy | 拷贝列表(浅拷贝)
user_list = ['alex','eric','jerry','tim','alven']
v = user_list.copy()
print(v)
print(user_list) ---
['alex', 'eric', 'jerry', 'tim', 'alven']
['alex', 'eric', 'jerry', 'tim', 'alven']
- 4.count | 计算列表里某个元素重复的个数
user_list = ['alex','eric','jerry','tim','alven','tim']
v = user_list.count('tim')
print(v) ---
2
- 5.extend | 扩展原列表
user_list = ['jerry','tim','alven']
user_list.extend(['beric','jakie'])
print(user_list) ---
['jerry', 'tim', 'alven', 'beric', 'jakie']
- 6.index | 查找元素索引/下标值;(没有则报错:ValueError: 'xxx' is not in list)
user_list = ['alex','eric','jerry','tim','alven']
v = user_list.index('tim')
# v = user_list.index('tim1')
print(v) ---
3
- 7.insert | 在 arg1 索引处插入 arg2 这个元素
user_list = ['alex','eric','jerry','tim','alven']
user_list.insert(0,'tom')
print(user_list) ---
['tom', 'alex', 'eric', 'jerry', 'tim', 'alven']
- 8.pop | 删除并且获取元素 (按照索引/下标值进行 pop; 不加参数则默认pop出最后一个元素)
user_list = ['alex','eric','jerry','tim']
# v = user_list.pop()
v = user_list.pop(2)
print(v)
print(user_list) ---
jerry
['alex', 'eric', 'tim']
- 9.remove | 删除列表中的某个元素,arg1 是列表中的值;
user_list = ['alex','eric','tim','alven']
user_list.remove('eric')
print(user_list) ---
['alex', 'tim', 'alven']
- 10.reverse | 翻转,将列表逆序
user_list = ['jerry','tim','alven']
print(user_list)
v = user_list.reverse()
print(v)
print(user_list) ---
['jerry', 'tim', 'alven']
None
['alven', 'tim', 'jerry']
- 11.sort | 排序(sort(self, key=None, reverse=False)); arg1 暂时没讲; arg2 True则是逆序,不写或者False就是顺序;
num_list = [11,3,8,99,21,4]
print(num_list)
num_list.sort()
print(num_list)
num_list.sort(reverse=True)
print(num_list) ---
[11, 3, 8, 99, 21, 4]
[3, 4, 8, 11, 21, 99]
[99, 21, 11, 8, 4, 3]
- 扩展补充
- 切片(和字符串切片类似)
li =['alex','eric','rain','tim','jerry']
print(li[0])
print(li[0:3])
print(li[0:4:2]) ---
alex
['alex', 'eric', 'rain']
['alex', 'rain']
- 删除(结合切片功能实现删除多个元素)
li =['alex','eric','rain','tim','jerry']
print(li)
del li[1:4]
print(li) ---
['alex', 'eric', 'rain', 'tim', 'jerry']
['alex', 'jerry']
- 求长度和 for 循环遍历
li =['alex','eric','rain','tim','jerry']
print(len(li))
for i in li:
print(i)
for i in range(0, len(li)):
print(li[i])
- 元组/tuple
- 类型 不可变(immutable)
user_tuple = ('alex','eric','alex',)
print(user_tuple[0])
user_tuple[0] = 'li' ---
alex
Traceback (most recent call last):
File "D:/soft/work/Python_17/day02/s03.py", line 27, in <module>
user_tuple[0] = 'li'
TypeError: 'tuple' object does not support item assignment
- 基础功能
- 1.count | 获取元素出现的个数
user_tuple = ('alex','eric','alex',)
v = user_tuple.count('alex')
print(v) ---
2
- 2.index | 获取指定元素第一个索引位置
user_tuple = ('alex','eric','alex',)
v = user_tuple.index('alex')
print(v) ---
0
- 扩展补充
- 元组赋值最后需要加一个 ','
li = ('alex') <-- 由于元组赋值最后没有加 ',' 导致被解释器理解为 str 类型
tpl = ('alex',) <-- 正确写法
print(type(li),li)
print(type(tpl),tpl) ---
<class 'str'> alex
<class 'tuple'> ('alex',)
- 长度可以用 len() 获取
- 循环遍历元组
user_tuple = ('alex','eric','alex',)
for i in user_tuple:
print(i) ---
alex
eric
alex
- 切片
user_tuple = ('alex','eric','jerry','mark','tim','li',)
print(user_tuple[0:2])
print(user_tuple[0:5:2])
print(user_tuple[-1])
print(user_tuple[-3:-1]) ---
('alex', 'eric')
('alex', 'jerry', 'tim')
li
('mark', 'tim')
- 关于元组里面嵌套列表
user_tuple = ('eric','seven',['谢霆锋','王旭','王强'],'alex',)
print(type(user_tuple), user_tuple, len(user_tuple))
print(user_tuple)
print(type(user_tuple[2]), user_tuple[2])
user_tuple[2][1] = '白百合'
print(user_tuple) ---
<class 'tuple'> ('eric', 'seven', ['谢霆锋', '王旭', '王强'], 'alex') 4
('eric', 'seven', ['谢霆锋', '王旭', '王强'], 'alex')
<class 'list'> ['谢霆锋', '王旭', '王强']
('eric', 'seven', ['谢霆锋', '白百合', '王强'], 'alex')
> 虽然元组是不可变类型,但是里面如果嵌套了可变类型的对象(列表、字典等),例如本例中的 list对象,则可以用 [user_tuple[2][1] = '白百合'] 类似方法去修改所嵌套对象的内部元素的值;
- 字典/dict
- 类型 可变类型
- 基础功能
- 1.clear | 清空一个字典
dic = {'k1':'v1','k2':'v2'}
print(dic)
dic.clear()
print(dic) ---
{'k2': 'v2', 'k1': 'v1'}
{}
- 2.copy | 拷贝一个字典(浅拷贝)
dic = {'k1':'v1','k2':'v2'}
v = dic.copy()
print(v)
print(dic) ---
{'k1': 'v1', 'k2': 'v2'}
{'k1': 'v1', 'k2': 'v2'}
- 3.get | 根据key获取指定的value;不存在则返回 None,不报错;
dic = {'k1':'v1','k2':'v2'}
v = dic.get('k1')
print(v)
v2 = dic.get('kxxx')
print(v2) ---
v1
None
- 4.items | 获取键值对
dic = {'k1':'v1','k2':'v2'}
for item in dic.items():
print(item) ---
('k1', 'v1') <-- 元组对象
('k2', 'v2')
- 5.keys | 获取字典键值
dic = {'k1':'v1','k2':'v2'}
for item in dic.keys():
print(item) ---
k2
k1
- 6.pop | 删除并获取对应的value值; arg1 不存在则报错;
dic = {'k1':'v1','k2':'v2'}
v = dic.pop('k1')
print(v)
print(dic) ---
v1
{'k2': 'v2'}
- 7.popitem | 随机删除键值对,并获取到删除的键值;
dic = {'k1':'v1','k2':'v2','k3':'v3'}
v = dic.popitem()
print(v)
print(dic) ---
('k2', 'v2') <-- 获取的是元组对象
{'k3': 'v3', 'k1': 'v1'}
- 8.setdefault | 增加一个元素,如果键值存在则不做操作;
dic = {'k1':'v1','k2':'v2'}
dic.setdefault('k3','v3')
print(dic)
dic.setdefault('k1','')
print(dic) ---
{'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}
{'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}
- 9.update | 批量增加和修改
dic = {'k1':'v1','k2':'v2'}
print(dic)
dic.update({'k3':'v3','k1':'v24'})
print(dic) ---
{'k1': 'v1', 'k2': 'v2'}
{'k3': 'v3', 'k1': 'v24', 'k2': 'v2'}
- 10.values | 获取字典值
dic = {'k1':'v1','k2':'v2'}
for item in dic.values():
print(item) ---
v2
v1
- 11.fromkeys | 原型:dict.fromkeys(seq[], value); 用于创建一个新字典,以序列seq中元素做字典的键,value为字典所有键对应的初始值。
dic = dict.fromkeys(['k1','k2','k3'],'China')
print(dic)
dic['k1'] = 'Beijing'
print(dic) ---
{'k2': 'China', 'k3': 'China', 'k1': 'China'}
{'k2': 'China', 'k3': 'China', 'k1': 'Beijing'}
- 扩展补充
- 1.默认显示键值
dic = {'k1':'v1','k2':'v2'}
for item in dic:
print(item) ---
k1
k2
- 2.字典可以嵌套
- 3.字典的键值必须是不可变类型(字符串、元组、整数、布尔值等都可以)
dic = {
'k1': 'v1',
'k2': [1,2,3,],
(1,2): 'tuple',
111: 'asdf',
True: 'china',
False: 'Japen', }
print(dic) ---
{'k1': 'v1', (1, 2): 'tuple', 'k2': [1, 2, 3], False: 'Japen', True: 'china', 111: 'asdf'}
- 关于True和1
dic1 = {
1: '',
True: 'True',
False: 'False',
}
dic2 = {
True: 'True',
1: '',
False: 'False',
}
print(dic1)
print(dic2) ---
{False: 'False', 1: 'True'}
{False: 'False', True: ''}
- 集合
- 类型 可变类型,可以理解为不可重复的列表,但是集合是无序的;
- 基础功能
- 1.add | 增加一个元素到集合
s1 = {'eric','tony','王阳明'}
print(type(s1),s1)
s1.add('袁崇焕')
print(type(s1),s1) ---
<class 'set'> {'tony', 'eric', '王阳明'}
<class 'set'> {'tony', 'eric', '袁崇焕', '王阳明'}
- 2.difference | s1.difference(s2) --> 列出s1中存在,s2中不存在的元素;
s1 = {'eric','tony','王阳明'}
s2 = {'eric','孙承宗','王阳明'}
v = s1.difference(s2)
v2 = s2.difference(s1)
print(v)
print(v2) ---
{'tony'}
{'孙承宗'}
- 3.difference_update | s1.difference_update(s2) --> s1中存在,s2中不存在,然后对s1清空,把对比出结果的赋值给s1
s1 = {'eric','tony','王阳明'}
s2 = {'eric','孙承宗','王阳明'}
print(s1)
s1.difference_update(s2)
print(s1) ---
{'tony', '王阳明', 'eric'}
{'tony'}
- 4.discard | 移除指定元素
s2 = {'eric','孙承宗','王阳明'}
s2.discard('eric')
print(s2) ---
{'王阳明', '孙承宗'}
- 5.intersection | 求交集
s1 = {'eric','tony','王阳明'}
s2 = {'eric','孙承宗','王阳明'}
v = s1.intersection(s2)
print(v) ---
{'eric', '王阳明'}
- 6.union | 求并集
s1 = {'eric','tony','王阳明'}
s2 = {'eric','孙承宗','王阳明'}
v = s1.union(s2)
print(v) ---
{'孙承宗', 'tony', '王阳明', 'eric'}
- 7.symmetric_difference | 求差集
s1 = {'eric','tony','王阳明'}
s2 = {'eric','孙承宗','王阳明'}
v = s1.symmetric_difference(s2)
print(v) ---
{'tony', '孙承宗'}
- 8.pop | 随机移除一个元素,并获取
s2 = {'eric','孙承宗','王阳明'}
v = s2.pop()
print(s2)
print(v) ---
{'王阳明', 'eric'}
孙承宗
- 9.remove | 删除指定值
s2 = {'eric','孙承宗','王阳明'}
s2.remove('eric')
print(s2) ---
{'王阳明', '孙承宗'}
- 10.update | 批量增加,如果有则忽略
s1 = {'eric','tony','王阳明','tim'}
s2 = {'eric','孙承宗','王阳明'}
s2.update(s1)
print(s2) ---
{'孙承宗', 'eric', 'tim', '王阳明', 'tony'}
- 扩展补充
- 1.set 不记录元素位置或者插入点(无序)。因此,set不支持 indexing, slicing, 或其它类序列(sequence-like)的操作;
- 2.可以用 len() 获取集合的长度;
- 3.可以循环遍历
s2 = {'eric','孙承宗','王阳明','白起','商鞅'}
for i in s2:
print(i) ---
商鞅
孙承宗
王阳明
eric
白起
- 4.可以把list对象去重:list2 = list(set(list1))
user_list = ['china','japan',(1,2),'china',(1,2),1]
print(type(user_list),len(user_list),user_list)
v = list(set(user_list))
print(type(v),len(v),v) ---
<class 'list'> 6 ['china', 'japan', (1, 2), 'china', (1, 2), 1]
<class 'list'> 4 [(1, 2), 1, 'china', 'japan']
四、关于循环的补充
- range 和 xrange
- range() | arg1 -> 起始计数; arg2 -> 终点计数; arg3 可选,代表的是步长;
for i in range(0,10,2):
print(i)
for j in range(10,0,-2):
print(j) ---
0
2
4
6
8
10
8
6
4
2
- Python 2.7
- range(1,10) 会立即在内存中生成10个数字;
- xrange(1,10) 不会立即生成,只有循环迭代时,才一个一个生成;
- Python 3.5
- 没有 xrange() 这个函数;
- range(1,10) 等价于 Py2.7中的 xrange(0,10)
- 常把 range() 和for循环结合使用,遍历数组或者字符串等。
- enumerate
- Python的内置函数,表示枚举、列举的意思
- 函数原型:enumerate(self, iterable, start=0); arg1 必须是可遍历的; arg2 可选,即设置起始的数据下标;
- 即对一个可遍历的数据对象(如列表、元组或字符串),enumerate会将该数据对象组合为一个索引序列,同时列出数据和数据下标
li =['alex','tim','jerry']
for i,ele in enumerate(li):
print(i,ele)
for i,ele in enumerate(li,100):
print(i,ele) ---
0 alex
1 tim
2 jerry
100 alex
101 tim
102 jerry
五、练习
要求:
"""
# 1. 练习题两个试卷:readme
# 2. 购物系统
- 个人账户,文件: user,pwd,3,余额
- 商品,文件
- 查看商品分页显示:
li = [
{...}
{...}
{...}
{...}
{...}
{...}
{...}
]
p = int(input('请输入页码:'))
start = (p -1) * 10
end = p * 10
v1 = li[start:end]
for i v1:
print(i)
- 个人购物记录,文件
查看:娃娃
if "al" in "alex":
pass
"""
代码实现:
#!/usr/bin/python
# -*- coding:utf-8 -*- import getpass
import time WARNING = "You have attempt 3 times which all wrong, so we have to lock your account to keep the security.\n\
You can contact the admin: admin@standby.pub"
GOODS_FILE = "D:\soft\work\Python_17\day02\goods_info.txt"
USERS_FILE = "D:\soft\work\Python_17\day02\\user_info.txt"
RECORD_FILE = "D:\soft\work\Python_17\day02\\record.txt"
OPTIONS = "Type 1 to buy, Type 2 to select your record; 9 to exit... >>>" # f.readlines() --> []
# f.open('file',mode='a',encoding='utf-8')
# user_info = "alex|123|0|900\neric|124|0|800\nrain|125|0|666\ntim|123|0|1000"
# with open('user_info.txt',mode='w',encoding='utf-8') as f:
# f.write(user_info) # 购物主函数
def do_shopping(user_name):
goods_list = []
buy_array = {}
with open(GOODS_FILE,mode='r',encoding='utf-8') as f:
goods_info = f.readlines()
for line in goods_info:
goods_dict = {
'name':line.split('|')[0],
'price':line.split('|')[1],
}
goods_list.append(goods_dict)
while True:
page_num = input("\nInput page num >>> ")
if page_num.isdigit():
num = int(page_num)
if 0 == len(goods_info)%3:
# // 整除 / 带余数
pages_num = len(goods_info)//3
else:
pages_num = len(goods_info)//3 + 1
if num >= 1 and pages_num >= num:
# 1 -> 0-2; 2 -> 3-5; 3 -> 6-8;...
start_num = num*3-3
end_num = num*3
tmp_list = goods_info[start_num:end_num]
for i,ele in enumerate(tmp_list,1):
line = '\t'.join(tmp_list[i-1].split('|')).expandtabs(20)
print("{}\t{}".format(i,line),end='')
while True:
toBuy = input("\nBuy something? y/Y to buy, n/N scan continue >>> ")
if toBuy.isalpha():
if 'Y' == toBuy.upper():
goods_num = input("Input the goods number: ")
if goods_num.isdigit():
if int(goods_num) > 0 and int(goods_num) <4:
count = input("How many do you want?\t\t")
if count.isdigit():
index = ((num-1)*3 + int(goods_num)) - 1
buy_array[index] = count
elif 'N' == toBuy.upper():
break
else:
print("Invalid input.")
else:
print("Invalid input.")
else:
print("{} pages only.".format(pages_num))
elif 'Q' == page_num.upper():
print("Bye...")
break
else:
print("Invalid input.")
print("++++++++++++++++++++++++++++++++++++")
print("You have choosen goods below: ")
print("++++++++++++++++++++++++++++++++++++")
sum = 0
buy_array_tmp = {}
for key,value in buy_array.items():
key_num = int(key)
good_name = goods_list[key_num]['name']
buy_array_tmp[good_name] = value
cost = int(goods_list[key_num]['price'])
costs = cost * int(value)
print(goods_list[key_num]['name'] + "\t" + "*" + "\t" + value)
sum += costs
print("++++++++++++++++++++++++++++++++++++")
print("++++++++++++++++++++++++++++++++++++")
confirm = input("Are you sure to buy them(y/n)?\t\t")
for i in range(0,len(user_list)):
if user_name == user_list[i]['name']:
money = user_list[i]['money']
user_id = i
if "y" == confirm:
if money < sum:
print("Sorry, your credit is running low...")
else:
do_record(user_name,buy_array_tmp)
user_list[user_id]['money'] = money - sum
print("The payment has been successfully completed and you have %d$ left." % (money - sum))
else:
print("Bye...")
exit(0) # 把当前用户购物记录追加到文件中
def do_record(username, buy_array_tmp):
line = "\n"
for goods_name,count in buy_array_tmp.items():
line = line + username + "|" + goods_name + "|" + count + "|" + \
time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
with open(RECORD_FILE,mode='a',encoding='utf-8') as f:
f.write(line) # 读取用户信息
def get_user_list():
user_list = []
with open(USERS_FILE,mode='r',encoding='utf-8') as f:
data = f.read()
user_info = data.split('\n')
for user in user_info:
user_dict = {'name': user.split('|')[0], 'pwd': user.split('|')[1],\
'times': int(user.split('|')[2]), 'money':int(user.split('|')[3])}
user_list.append(user_dict)
return user_list # 查找购物记录
def do_select_record(user_name):
while True:
key = input("Input keyword, q/Q to exit >>> ")
if 'Q' != key.upper():
with open(RECORD_FILE,mode='r',encoding='utf-8') as f:
record_list = f.readlines()
flag = -1
for record in record_list:
if user_name in record and key in record:
print(record)
flag = 0
if -1 == flag:
print("No record found...")
else:
break # 执行操作前的判断
def do_something(user_name):
options = input(OPTIONS)
if options.isdigit():
if 1 == int(options):
do_shopping(user_name)
elif 2 == int(options):
do_select_record(user_name)
elif 9 == int(options):
print("Bye...")
exit(0)
else:
print("Invalid input.")
do_something(user_name)
else:
print("Input not number, type again...")
do_something(user_name) # 用户登录验证
def login():
count = 0
while count < 3:
name = input("Please input your name: ")
flag = -1
for item in user_list:
if item['name'] == name:
if item['times'] >= 3:
print(WARNING)
exit(0)
else:
count = 0
flag = 0
pwd = getpass.getpass("Please input your password: ")
if item['pwd'] == pwd:
print("Welcome %s." % name)
item['times'] = 0
count = 3
do_something(name)
else:
if 0 == 2-item['times']:
pass
else:
print("Wrong password, you have %s times to retry." % (2-item['times']))
item['times'] += 1
if item['times'] >= 3:
print(WARNING)
count = 3
break
if -1 == flag:
print("Invalid account, please check your user name...")
count += 1 # 程序入口
user_list = get_user_list()
login() # 程序执行结束,格式化用户信息并写回文件
result = ""
for item in user_list:
user_info_str = item['name'] + "|" + item['pwd'] + "|" + str(item['times']) + "|" + str(item['money'])
result = result + user_info_str + "\n"
f2 = open(USERS_FILE,'w')
f2.write(result.strip())
f2.close()
涉及到的文件:
user_info.txt:
---
alex|123|0|90000
eric|124|3|800
rain|125|0|23
tim|123|0|9619
--- goods_info.txt
---
Linux v1|129
Solaris beta|322
Free BSD|666
AWK cookbook|79
GO lang|88
Python lang|57
CentOS 6.6|333
CentOS 5.9|103
Unix-like 9|999
艽野尘梦|59
--- record.txt
---
alex|Linux v1|1|2017-05-15 23:37:53
alex|GO lang|1|2017-05-15 23:37:53
alex|艽野尘梦|3|2017-05-15 23:37:53
tim|CentOS 6.6|3|2017-05-15 23:42:26
tim|艽野尘梦|1|2017-05-15 23:42:26
tim|AWK cookbook|2|2017-05-15 23:42:26
tim|艽野尘梦|1|2017-05-15 23:48:52
rain|Free BSD|1|2017-05-15 23:50:58
rain|Solaris beta|2|2017-05-15 23:52:39
tim|Solaris beta|1|2017-05-15 23:53:23
---