数据类型
字符串(String)
当字符串被创建时,修改或删除字符串的一部分是不允许的。这是因为字符串是不可变的,因此一旦分配了字符串,就无法更改其元素。 只能将新字符串重新分配给相同的名称。
>>> str_1[-1] = 'c'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> del str[2]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'type' object does not support item deletion
但是,删除整个字符串是允许的。
>>> del str_1
>>> print(str_1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'str_1' is not defined
无视转义字符
的两种方法:
>>> str_2 = 'hello \\n world'
>>> print(str_2)
hello \n world
>>> print(r'hello \n world')
hello \n world
列表(List)
添加:
a.append(2)
删除:
a.pop()
a.remove()
字典
最常用:
a.setdefault(1,'one')
#更新字典
In [8]: a
Out[8]: {}
In [9]: b = {1:'one'}
In [10]: a.update(b)
In [11]: a
Out[11]: {1: 'one'}
取“键”,“值”
a.keys() #所有键
a.values() #所有值
#判断
key in a
#获取值
a.get(1)
字符串
判断字符串中是否有某个子串:
>>> 'he' in 'hello'
True
>>> 'se' in 'hello'
False
变量
Global关键字:
当出现以下程序逻辑时会报错:
In [1]: a = 1
In [2]: def f():
...: a = a + 1
In [3]: f()
---------------------------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
<ipython-input-5-c43e34e6d405> in <module>
----> 1 f()
<ipython-input-4-188099e9dbd2> in f()
1 def f():
----> 2 a = a + 1
3
UnboundLocalError: local variable 'a' referenced before assignment
原因是a是全局变量,当函数内出现和a同名的变量时,python自动将其视为局部变量,局部变量的作用域仅限于函数内,在没有分配内存前引用局部变量就会报错。
如果明确指定a是全局变量,要使用global关键字:
In [6]: def f():
...: global a
...: a = a + 1
...:
In [7]: f()
变量转换
常见的有:
- list()
- tuple()
- str()
- float()
- set()
- dict()
将格式为(key,value)的元组传递给dict()
>>> tup = (('a', 1) ,('f', 2), ('g', 3))
>>> dict(tup)
{'a': 1, 'f': 2, 'g': 3}
字符串转换为整型:
>>> s = "1001"
>>> int(s)
1001
>>> int(s,2)
9
将字符转换为ASCII码值:
>>> ascii = ord('c')
>>> ascii
99
十进制数转换为十六进制数
>>> print(hex(34))
0x22
十进制数转换为八进制数
>>> print(oct(34))
0o42
实数转换为复数表示
>>> complex_num = complex(5)
>>> complex_num
(5+0j)
输入/输出
从命令行获取一个
输入:
>>> a = input('Enter something:')
Enter something:hello
>>> a
'hello'
input()默认获取的数据类型是str
,如果需要其他类型,要使用数据转换。
有两种方法可以获取多个
输出:
- split()
- 列表推导式
split()
输入格式为:input().split(separator=‘ ’, maxsplit)
>>> a,b,c = input('Enter 3 number:').split()
Enter 3 number:1 2 3
>>> print(a,b,c)
1 2 3
列表推导式
>>> x,y = [int(x) for x in input().split()]
1 2
>>> print(x,y)
1 2
>>> a = [int(x) for x in input().split()]
1 2 3
>>> print(a)
[1, 2, 3]
使用print()函数打印输出:
输入格式为:print(value(s), sep= ‘ ‘, end = ‘\n’, file=file, flush=flush)
- value(s) : Any value, and as many as you like. Will be converted to string before printed
- sep=’separator’ : (Optional) Specify how to separate the objects, if there is more than one.Default :’ ‘
- end=’end’: (Optional) Specify what to print at the end.Default : ‘\n’
- file : (Optional) An object with a write method. Default :sys.stdout
- flush : (Optional) A Boolean, specifying if the output is flushed (True) or buffered (False). Default: False
end关键字
可用于把输出保持在同一行。
>>> a = [x for x in range(5)]
>>> print(a,end=' ')
[0, 1, 2, 3, 4]
sep关键字
控制分隔符:
>>> print('09','12','2016', sep='-')
09-12-2016
格式化输出:
Formatting output using
String modulo operator(%)
:
>>>print("epoch: %d , loss: %4f" % (epoch, loss_sum))
>>>epoch: 0 , loss: 0.613527 , accuracy: 0.763110
Formatting output using
format
method
使用{}
来表示输出变量,并且能提供详细的命令:
>>> print("{} {}".format('hello','world'))
hello world
‘0’和‘1’可以表示位置:
>>> print("{1} {0}".format('hello','world'))
world hello
结合位置参数和关键字参数:
>>> print("{1} {0} {other}".format('hello','world',other='forever'))
world hello forever
对数字添加约束:
>>> print("Second argument: {1:3d}, first one: {0:7.2f}".
... format(47.42, 11))
Second argument: 11, first one: 47.42
{1:3d}表示在位置1输出格式为3d的整型数字。
使用字典输出:
>>> dit = dict(one=1,two=2)
>>> print("{one},{two}".format(**dit))
1,2
函数参数带*号
可以把参数当作元组输入
def get_char(r,g,b):
print(r,g,b)
input = [1,2,3]
get_char(*input)
1 2 3
迭代器和生成器
迭代器是一个可以记住遍历的位置的对象。迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束。迭代器只能往前不会后退。迭代器有两个基本的方法:iter() 和 next()
a = [1,2,3]
b = iter(a)
for x in b:
print(x,end=' ')
a = iter([1,2,3])
while true:
try:
print(next(a))
except StopIteration:
pass
StopIteration
异常用于标识迭代的完成,防止出现无限循环的情况
创建一个迭代器
把一个类作为一个迭代器使用需要在类中实现两个方法 iter() 与 next() 。
读写文件
#读
with open('1.txt','rt') as f:
for line in f:
...
f = open('1.txt','rt')
data = f.read()
f.close()
#写
with open('1.txt','wt') as f:
f.write()
PILLOW库
打开图片
from Pillow import Image
im = Image.open(IMG)
查看图片大小
width,height = im.size
调整图片大小
im = im.resize((WIDTH,HEIGHT), Image.NEAREST)
获取像素值
pixel = im.getpixel((i,j))
print(pixel)
显示图片
im.show()
argparse库
import argparse
#命令行输入参数处理
parser = argparse.ArgumentParser()
parser.add_argument('file') #输入文件
parser.add_argument('-o', '--output') #输出文件
parser.add_argument('--width', type = int, default = 80) #输出字符画宽
parser.add_argument('--height', type = int, default = 80) #输出字符画高
#获取参数
args = parser.parse_args()
IMG = args.file
WIDTH = args.width
HEIGHT = args.height
OUTPUT = args.output
Numpy
np.tile(input,reps)
构造数组,对原来数组元素重复n次。reps可以是int型,也可以是元组。
>>> a = np.array([1,2,3])
>>> a
array([1, 2, 3])
>>> np.tile(a,2)
array([1, 2, 3, 1, 2, 3])
>>> np.tile(a,(2,3))
array([[1, 2, 3, 1, 2, 3, 1, 2, 3],
[1, 2, 3, 1, 2, 3, 1, 2, 3]])
np.dot(a,b,out=None)
可用于矩阵乘法:
>>> X
array([[ 1.09129258, -0.64508607, 0.96719203],
[ 1.97342373, 0.82250226, -0.6966815 ],
[ 0.51487429, -2.94723696, 1.3355403 ],
[ 0.22526178, -0.61112564, 2.45981389]])
>>> W
array([[-1.54807435, 0.86783411],
[ 0.6731317 , 1.41302845],
[-0.93865381, 1.09652789]])
>>> X.dot(W)
array([[-3.03148841, 1.09608899],
[-1.84741157, 2.11089283],
[-4.03455231, -2.253247 ],
[-3.06900371, 2.02920648]])
np.maximum(x,y)
逐个对比数组元素,保留最大值
>>> np.maximum([2, 3, 4], [1, 5, 2])
array([2, 5, 4])
OS
判断文件是否存在,如果不存在就返回False
os.path.isfile('test.txt')
判断文件夹是否存在,如果目录不存在就返回False
os.path.exists(directory)
创建文件夹
os.mkdir()
删除文件
os.remove('path')
查看当前工作目录
os.getcwd()
改变当前工作目录
os.chdir('C:\\Users\\85233\\Desktop\\课程相关\\多媒体通信')
Shutil
清空文件夹下所有的文件
shutil.rmtree('要清空的文件夹名')
Matplotlib库
绘制折线图
from matplotlib import pyplot as plt
plt.plot(X,Y)
设置坐标轴名称
plt.xlabel('xxxxxxxxxxx')
plt.ylabel('yyyyyyyyyyy')