【Python】Day 2

自学python第二天内容

一、列表的使用

1、赋予变量元素,打印出来

1
2
names=["111","222","333","444"]
print(names)

2、增加元素

1
2
3
4
names=["111","222","333","444"]
names.append("555")#自动添加到最后面
names.insert(0,"666")#添加到指定位置
print(names)

3、修改元素

1
2
3
4
names=["111","222","333","444"]
names[0]="777"
print(names)
4、删除元素
1
2
3
names=["111","222","333","444"]
names.remove("111")
del names[1]

names.pop(2)#默认删除最后一个元素
5、查找元素

1
2
3
names=["111","222","333","444"]
print("----->>",names.index("222"))#显示位置
print("----->>",names[names.index("222")])#直接显示结果

6、反转元素

1
2
names=["111","222","333","444"]
name.reverse()

7、排序元素

1
2
names=["111","222","333","444","aaa","AAA","#123","1qwe"]
names.sort()#按照ansi码排序

8、拼接元素

1
2
3
4
numbers=["1111","2222"]
names=["111","222","333","444"]
names.extend(numbers)
print(numbers,names)#保持原有变量不变

8、复制元素

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
(1)
names1=["111","222",["333","555"],"444"]
names2=names1.copy()
print(names1)
print(names2)
print("---------------------->>")
names1[0]="222"
print(names1)
print(names2)
print("---------------------->>")
names1[2][1]="666"
print(names1)
print(names2)
 
运行结果:
['111', '222', ['333', '555'], '444']
['111', '222', ['333', '555'], '444']
---------------------->>
['222', '222', ['333', '555'], '444']
['111', '222', ['333', '555'], '444']
---------------------->>
['222', '222', ['333', '666'], '444']
['111', '222', ['333', '666'], '444']
#所以此copy为浅copy,只copy第一层
(2)
import copy
 
 
names1=["111","222",["333","555"],"444"]
names2=copy.deepcopy(names1)
print(names1)
print(names2)
print("---------------------->>")
names1[0]="222"
print(names1)
print(names2)
print("---------------------->>")
names1[2][1]="666"
print(names1)
print(names2)
运行结果:
['111', '222', ['333', '555'], '444']
['111', '222', ['333', '555'], '444']
---------------------->>
['222', '222', ['333', '555'], '444']
['111', '222', ['333', '555'], '444']
---------------------->>
['222', '222', ['333', '666'], '444']
['111', '222', ['333', '555'], '444']
 
 
 
#需引用copy模块,才能深copy,并且要用deepcopy

9、元组(tuple)

1
2
names=("111","222","333")
#元组又叫只读列表,只能切片和查,只有两个方法,count和index

二、sys,os模块

1、输出此程序的路径

1
2
import sys
print(sys.argv)

2、显示所在目录的文件

1
2
3
4
5
6
7
(1)
import os
cmd_res=os.system("dir")#执行命令,不保存结果!
(2)
cmd_res=os.popen("dir").read()
os.mkdir("new_dir")#创建文件
print("-->",cmd_res)

3、字符串编码成二进制,二进制解码成字符串

1
2
3
4
msg=("你是谁?")
print(msg)
print(msg.encode("utf-8"))
print(msg.encode("utf-8").decode("utf-8"))#encode是编码,decode是解码,默认用utf-8

 

1
 

About the Author

发表评论

电子邮件地址不会被公开。