微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python学习笔记2

本章:

  1.列表、元组操作

  2.字符串操作

  3.字典操作

  4.集合操作

  5.文件操作

  6.字符编码与转码

 

一.列表、元组操作

列表是我们最常用的数据类型之一,通过列表可以对数据实现最方便的存储、修改等操作。

定义列表:

1 name = ['1','2','3']  #定义列表
2 print(name)  打印列表

通过下标访问列表中的元素:

1 name = ['1','2','3']
2 print(name[0])    #第一个位置是从0开始计数的
3 1
4 print(name[1])
5 2
6 print(name[2])
7 3
8 print(name[-2])   #也可以写倒着写,用负数表示
9 2

追加:  *.append()   *:列表的名称,以下*代表相同意思

1 name = ['1','2','3']
2 name.append( ("new1","new2") ) #可以追加一组
3 name.append("new3")        #可以追加一个
4 print(name)
5 ['1', '2', '3', ('new1', 'new2'), 'new3']

 

插入: *.insert  

1 name = ['1','3','5','7','9']
2 name.insert(4,"8")    #在第四个字符串前插插入一行
3 print(name)
4 ['1', '3', '5', '7', '8', '9']

修改

1 >>> name = ["A","B","C","D"]
2 >>> name[2]= "new c"        ##定义第2个字符串赋予新的值
3 >>> print(name)
4 ['A', 'B', 'new c', 'D']

删除:del、*.pop、*.remove

 1 >>> name = ["A","B","C","D"]
 2 >>> del name[2]      #删除指定字符串,这里2代表字符串所在标注的位置
 3 >>> print(name)
 4 ['A', 'B', 'D']
5 >>> name = ["A","B","C","D"] 6 >>> name.pop()      #删除最后一个字符串 7 >>> print(name) 8 ['A', 'B', 'C']
9 >>> name = ["A","B","C","D"] 10 >>> name.remove("A")  #删除指定的字符串;直接写字符串; 11 >>> print(name) 12 ['B', 'C', 'D']

扩展: *.extend

1 >>> name = ["A","B","C","D"]
2 >>> names = ["E","F","G"]
3 >>> name.extend(names)
4 print(name)

拷贝: 

 1 >>> name = ["A","B","C","D"]
 2 >>> names = name.copy()
 3 >>> name[2] = "new c" 4 print(names)
 5 ['A', 'B', 'C', 'D']         #只拷贝一层,先拷贝,然后修改,拷贝出来的内容修改之前的
 
 6 >>> import copy   #调用模块   #深层拷贝,拷贝后,如果对数据进行修改,拷贝出的内容修改以后的
 7 >>> names = ["ZhangYang","GuYun","HanYunHui","2JinYang","JinYang",["1","2"] ]
 8 >>> name2 = copy.deepcopy(names)
 9 >>> names[0] = "jinyang"
10 >>> print(names)
11 ['jinyang', 'GuYun', 'HanYunHui', '2JinYang', 'JinYang', ['1', '2']]

统计&获取下标

1 >>> name = ["1","1","2","2","3"]
2 >>> print(name.count("1"))      ##统计列表中有多少"1"字符串
3 2        
4 >>> name = ["1","1","2","2","3"]
5 >>> print(name.index("2"))      ##获取"2"下标位置,如果有重复,只返回第一个所在下标的位置
6 2
7 >>> name = ["1","1","2","2","3"]
8 >>> print(name[name.index("3")])  ##可以嵌套查出内容;先获取"3"字符串下标位置,然后根据下标打印出相应的字符串
9 3

排序&反转   *.sort:排序  *.reverse:反转

1 >>> name = ["name","3","1","Name","MEm","t1","#1"]
2 >>> name.sort()      ##排序
3 >>> print(name)
4 ['#1', '1', '3', 'MEm', 'Name', 'name', 't1']
5 >>> name.reverse()    #反转
6 >>> print(name)
7 ['t1', 'name', 'Name', 'MEm', '3', '1', '#1']

切片:获取多个元素

 1 name = ["0","1","2","3","4","5","6"]
 2 >1> print(name[3],name[1])      ##读取下标3和下标1字符串
 3 >2> print(name[1:5])            ##读取下标1至下标5之间的字符串,但不包括下标5对应的字符串
 4 >3> print(name[1:-1])           ##读取下标1到倒数第一行之间的字符串,但不包括倒数第一行字符串
 5 >4> print(name[0:3])            ##读取下标0至下标3之间的字符串,但不包括下标3
 6 >5> print(name[:3])             ##与上面一致,主要提出出前面那个0可以省略;后面0也可也省略,例如:1:0 可以写成1:
 7 >6> print(name[0::3])           ##后面3代表每隔两个元素,读取一次
 8 
 9 >1> 3 1
10 >1> ['1', '2', '3', '4']
11 >1> ['1', '2', '3', '4', '5']
12 >1> ['0', '1', '2']
13 >1> ['0', '1', '2']
14 >1> ['0', '3', '6']

 

元组元组和列表类似,元组使用小括号(),列表使用中括号[]

 参考具体用法:https://www.runoob.com/python3/python3-tuple.html

 

 

 

二.字符串操作

 

print('name'.capitalize())       
>>Name                   ##把第一个字符串首字母变成大写 print('NAME'.casefold())        
>>name                   ##把所有大写变成小写 print("han".center(10,"-"))
>>---han----               ##格式,写10个字符串不够用-代替,同时han居中
print('A A A A A'.count('A'))
>>5                     ##统计有多少字符串 print('A'.encode())
>>                 ##把字符串变成byte字符串 print(type('A'))
>><class 'str'>             ##打印字符串类型 print('my name is hanyunhui'.endswith('hui'))  
>>true                         ##判断字符串以什么结尾,正确返回true,错误返回false print('han\tyun'.expandtabs(10))     
>>han yun                 ##把\t 变成多个空格 print('hanyunhui'.find('h'))   
>>0                          ##查找字符串,返回的值是字符串所在下标的位置;如果有重复返回第一个值所在位置
print('hanyunhui'.rfind('n')
>>5                          ##查找字符串,如果有重复返回最后一个字符串所在位置; print('hanyunhui'['hanyunhui'.find('han'):5])
>>hanyu                        ##先查找字符串,先查找字符串换下标位置,下标到下标5之间的字符串
print('223223'.replace('2','1',3))    
>>113123                    ##替换;把2替换成1,后面的3代表替换的次数
print('hanyunhui'.swapcase())
>>HANYUNHUI                     ##把小写变成大写
print('han yun hui'.title())          
>>Han Yun Hui                    ##把首字母变成大写
print('hanyunhui'.split('n'))
>>['ha','yu','hui']                ##提取某个字段当成分隔符
print('1+2+3+4'.split('+'))
>>['1','2','3','4']
print('1+2+3\n+4'.split('\n'))
>>['1+2+3','+4']                  ##把换行符当做分割符号
print('1+2+3\n+4'.splitines())
>>['1+2+3','+4']                 ##与上面作用一致

 

 

 

三.字典操作

字典是一种key-value的数据类型;key必须是唯一的,不能重复;value是无序的;

语法:

info = {
    '001':'zhangsan',
    '002':'lisi',
    '003':'wangwu'
}
'001','002','003':属于key值,必须唯一,不能重复;
'zhangsan','lisi','wangwu':valuse值,无序的;

增加:  修改,如果key存在则是修改;如果不存在则是新增;

info ['004'] = 'zhaoliu'
print(info)
{'001': 'zhangsan', '002': 'lisi', '003': 'wangwu', '004': 'zhaoliu'}

删除

info = {'001':'zhangsan','002':'lisi','003':'wangwu'}
print(info.pop('001'))    ##标准删除
print(info.popitem())     ##随机删除
del info['002']       ##通用删除

查找:

info = {'001':'zhangsan','002':'lisi','003':'wangwu'}
print('004' in info)    ##标准查询,如果存在返回true,如果不存在返回false
print(info.get('004'))   ##如果存在返回valse值,如果不存在返回none值
print(info['003'])        ##如果妇女在返回valse值,如果不存在则会提示报错

多级嵌套:

 1 info = {
 2     "中国":{
 3         "北京":{'东城','西城'},
 4         "上海":{'陆家嘴','虹桥'},
 5     },
 6     "日本":{
 7         "东京":{'富士山','火山'},
 8         "樱花":{'相扑','生鱼片'}
 9     },
10     "韩国":{
11         "首尔":{'整容','泡菜'},
12         "济州岛":{'大海','清册'}
13     }
14 }

其他用法

info = {'001':'zhangsnan','002':'lisi','003':'wangwu'}
print(info.keys())
>>dict_keys(['001', '002', '003'])         ##打印key值
print(info.values()) >>dict_values(['zhangsan', 'lisi', 'wangwu'])  ##打印valuse值
print(info.setdefault("004":'ZhangSan'))     ##如果key值存在打印valuse值,如果key值不存在打印自己的valuse值 >>zhangsnan b = {1:2,3:4,'002':"LiSi"} info.update(b) print(info) >>{'001': 'zhangsnan', '002': 'LiSi', '003': 'wangwu', 1: 2, 3: 4}     ##更新 print(info.items()) >>dict_items([('001', 'zhangsnan'), ('002', 'LiSi'), ('003', 'wangwu'), (1, 2), (3, 4)])

循环dict

1 info = {'001':'zhangsnan','002':'lisi','003':'wangwu'}
2 
3 for key in info:
4     print(key,info[key])
5 
6 for k,v in info.items():
7     print(k,v)

 

 

四.集合操作

集合是一个无序,不重复的数据组合,主要作用:

  • 去重,把一个列表变成集合,就自动去重
  • 关系测试,测试两组数据之间的交集、差集、并集等关系

常用操作:

A = set({1,2,3,4})
B = set({4,5,6,7})

#并集;去掉重读部分结合起来
print(A | B)
print(A.union(B))
>>>{1,2,3,4,5,6,7}

#交集;只打印有交集的部分
print(A & B)
print(A.intersection(B))
>>>{4}

#差集;打印不同的部分,注意那个表在前面就打印那个表的内容
print(A - B , B - A)
print(A.difference(B),B.difference(A))
>>>{1,2,3}{5,6,7}

#对称差集;打印出两个表所不同部分
print(A ^ B)
print(A.symmetric_difference(B))
>>>{1,2,3,5,6,7}

#判断两个文件是都有交集;没有返回true,有返回false
print(A.isdisjoint(B))

#子集
A = set({1,2,3,4,5,6})
B = set({5,6})
print(A.issuperset(B))  #判断子集;正确返回true,不是返回false
print(B.issubset(A))    #判断父集;正确返回true,不是返回false
print('====================')

A.add(99)                #增加一项
A.update([1000,1001,1002])   #添加多项
A.pop()            #随机删除一项
A.remove(2)              #指定删除一项;当删除项不存在时提示报错
A.discard(3)            #指定删除一项;当删除项不存在时无反应

#####################
A = set({1,2,3,4,'n'})
B = set({4,5,6,7})

print(len(A))        #测试A的长度
print('n' in A)         #测试n是都在A集合中;如果存在返回true值
print('5' not in A)               #测试5是都在A集合中;如果不存在返回true值

 

 

 

五.文件操作

open() 函数常用形式是接收两个参数:文件名(file)和模式(mode);open(file,mode='r')

详细查看菜鸟教程中file办法:https://www.runoob.com/python/file-methods.html

文件操作流程:

  1. 打开文件,得到文件句柄并赋值给一个变量
  2. 通过句柄对文件进行操作
  3. 关闭文件

文件如下:

 1 Sunday's coming I wanna drive my car
 2 这周日我想开着我的爱车
 3 To your apartment with the present like a star
 4 像明星一样带着的礼物去你的公寓
 5 Forecaster said the weathers may be rainy hard
 6 天气预报说天气糟透了
 7 But I kNow the sun will shine for us
 8 但是太阳会为我们闪耀
 9 Oh lazy seagull fly me from the dark
10 喔~慵懒的海鸥引领我走向光明
11 I dress my jeans and Feed my monkey banana
12 穿上我的牛仔,给猴子喂了点香蕉
13 Then I think my age how old,skyline how far
14 我想到,我有多大,地平线有多远
15 Or we need each other in California
16 喔~在加州我们需要彼此
17 You show me your body before night comes down
18 夜幕降临前你向我展示你诱人的身姿
19 I touch your face and promise to stay ever young
20 我抚摸你的脸颊,许下永远像年轻时爱你的诺言
21 On this ivory beach we kissed so long
22 我们深情拥吻在这象牙色的海滩
23 It seems that the passion's never gone
24 仿佛激情永不逝
25 You sing me your melody and I feel so please
26 你为我哼唱你的曲子,幸福感冲昏了我的脑袋
27 I want you to want me to keep your dream
28 我希望你也让我永远怀揣你的梦想
29 Together we'll run wild by a summer symphony
30 在夏夜的交响乐中我们狂野的奔跑
31 This is what we enjoyed not a fantasy
32 我们享受的不再是幻想
33 
34 The tin-man's surfing I wanna try my luck
35 我想去冲浪
36 To the top of tide rip like just have some ***
37 在浪尖舞动就像***一样
38 I kNow you have no blame for my proud moonish heart
39 你不会责备我骄傲易变的心
40 Welcome to the golden beatnic park
41 欢迎来到黄金beatnic庄园
42 Oh diamond seashore drag me from the yard
43 钻石般的海岸指引我园外风光
44 Incredible sunward I watch as you're in photograph
45 你为这动人的景色添姿加彩
46 For camera your smile's so sweet,palm trees' so lush
47 对着镜头,你笑的如此的甜,就像棕榈树青翠欲滴
48 Would you believe my honey it's California
49 亲爱的,你会相信我吗,这就是加州
50 You show me your body before night comes down
51 夜幕降临前你向我展示你诱人的身姿
52 I touch your face and promise to stay ever young
53 我抚摸你的脸颊,许诺我们永远这样年轻
54 On this ivory beach we kissed so long
55 我们深情拥吻在这象牙色的海滩
56 It seems that the passion's never gone
57 仿佛激情永不逝
58 You sing me your melody and I feel so please
59 你为我哼唱你的曲子,幸福感冲昏了我的脑袋
60 I want you to want me to keep your dream
61 我希望你也让我永远怀揣你的梦想
62 Together we'll run wild by a summer symphony
63 在夏夜的交响乐中我们狂野的奔跑
64 This is what we enjoyed not a fantasy
65 我们享受的不再是幻想
View Code

 基本操作:

f = open('gala.txt','r')      #open 是打开文件 
data = f.read()               #赋值变量
print(data)                   #打印内容     
f.close()                     #关闭文件

基本用法

“+”表示可以同时写某个文件

  •  r+:可读可写
  • w+:写读
  • a+:和a用法一致

 “u”表示在读取时,可以将\r \n \r\n 自动转换成\n(与r或r+模式同使用)

  • ru
  • r+u

“b”表示处理二进制文件(如:FTP发送上传iso镜像文件,linux可忽略,windows处理二进制文件时需标注)

  • rb
  • wb
  • ab

基本用法

 1 #往文件里写;
 2 f = open('gala.txt','w')
 3 print(f.write('Sunday s coming I wanna drive my car\n'))
 4 print(f.write('这周日我想开着我的爱车\n'))
 5 f.close()
 6 
 7 #往文件里追加;认是追加到后面;
 8 f = open('gala.txt','a')
 9 print(f.write('To your apartment with the present like a star\n'))
10 print(f.write('像明星一样带着的礼物去你的公寓\n'))
11 f.close()
12 
13 f = open('gala.txt','a')
14 print(f.write('Forecaster said the weathers may be rainy hard\n'))
15 print(f.write('天气预报说天气糟透了'))
16 f.close()
17 
18 ##############################
19 f = open('gala.txt','r+')
20 print(f.readline())     #只读取一行
21 print(f.readline())     #只读取一行
22 print(f.readlines())    #读取所有行
23 #高端写法;一行一行读取文件内容;
24 count = 0
25 for line in f:
26     count +=1
27     if count == 9:
28         print('-----woshi fen-----')
29         continue
30     print(line)
31 
32 
33 print(f.seek(10))    #把光标移动到指定位置
34 print(f.tell())     #查看光标位置
35 print(f.encoding)   #查看字符集编码
36 print(f.truncate(10))    #截断,从指定位置到末尾截断
37 print(f.flush())         #刷新缓冲区;

with语句

   为了避免打开文件后忘记关闭,可以通过管理上下文方式,当执行完毕时会自动关闭并释放文件资源,即:

1 #之前用法
2 f = open('gala.txt','r+')
3 print(f.readlin())
4 
5 #with用法;在with下执行语句
6 with open('gala.txt','r+') as f:
7     print(f.readline())

 

 

 

 

6.字符编码与转码

  • python3认是unicode编码
  • unicode分为utf-32(占4字节),utf-16(占两个字节,是最常用的unicode版本),utf-8(占1-4字节)
  • 在py3中encode在转码的同时还会把string变成bytes类型,decode在解码的同时还会把bytes变回string

 

GBK转UTF-8格式流程:

  • 首先通过编码【decode】转换为unicode编码
  • 再通过解码【encode】转换为utf-8

UTF-8转GBK格式流程:

  • 首先通过编码【decode】转换为unicode编码
  • 再通过解码【encode】转换为GBK

 

 

open() 函数常用形式是接收两个参数:文件名(file)和模式(mode)。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐