0%

python常用语法

Python常用语法

基础

安装包

1
2
3
# 以下载numpy为例
pip install numpy -i http://mirrors.aliyun.com/pypi/simple/
pip3 install torch==2.0.0+cu118 -i http://mirrors.aliyun.com/pypi/simple/

默认使pip官方的下载链接,在国外,一般使用国内的镜像网址:

1
2
3
4
https://pypi.tuna.tsinghua.edu.cn/simple/
http://mirrors.aliyun.com/pypi/simple/
http://pypi.douban.com/simple/
https://pypi.mirrors.ustc.edu.cn/simple/

pip 永久换源

1
pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/

输入输出

1
2
3
4
5
# 格式化输出
>>> print("The length of %s is %d" % (s,x))
The length of Hello is 5
>>> print("The length of {} is {}".format(s, x))
The length of Hello is 5

类型转换

转换 转换前
十转二 bin(10) ‘0b1010’
十转八 oct(9) ‘0o11’
十转十六 hex(15) ‘0xf’
转为字符串 i = 100
str(i)
‘100’
十转ASCII chr(65) ‘A’
ASCII转十 ord(‘A’) 65

生成随机数

1
2
import random
rnd = random.randint(1,500) #生成1-500之间的随机数
1
2
# 不换行输出
print('*', end='')

string

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
str1 = 'hello, world!'
print(len(str1)) # 计算字符串的长度 13
print(str1.capitalize()) # 获得字符串首字母大写的拷贝 'Hello, world!'
print(str1.upper()) # 获得字符串变大写后的拷贝 'HELLO, WORLD!'
print(str1.find('or')) # 从字符串中查找子串所在位置 8
print(str1.find('shit')) # -1
# 与find类似但找不到子串时会引发异常
# print(str1.index('or'))
# print(str1.index('shit'))
# 检查字符串是否以指定的字符串开头
print(str1.startswith('He')) # False
print(str1.startswith('hel')) # True
# 检查字符串是否以指定的字符串结尾
print(str1.endswith('!')) # True
# 将字符串以指定的宽度居中并在两侧填充指定的字符
print(str1.center(50, '*'))
# 将字符串以指定的宽度靠右放置左侧填充指定的字符
print(str1.rjust(50, ' '))

str2 = 'abc123456'
# 从字符串中取出指定位置的字符(下标运算)
print(str2[2]) # c
# 字符串切片(从指定的开始索引到指定的结束索引)
print(str2[2:5]) # c12
print(str2[2:]) # c123456
print(str2[2::2]) # c246
print(str2[::2]) # ac246
print(str2[::-1]) # 654321cba
print(str2[-3:-1]) # 45
# 检查字符串是否由数字构成
print(str2.isdigit()) # False
# 检查字符串是否以字母构成
print(str2.isalpha()) # False
# 检查字符串是否以数字和字母构成
print(str2.isalnum()) # True
str3 = ' jackfrued@126.com '
print(str3.strip()) # 获得字符串修剪左右两侧空格的拷贝 'jackfrued@126.com'

list

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
list1 = [1, 3, 5, 7, 100]
list2 = ['hello'] * 5
# 计算列表长度(元素个数)
print(len(list1))
# 下标(索引)运算
print(list1[0])
print(list1[4])
# print(list1[5]) # IndexError: list index out of range
print(list1[-1])
print(list1[-3])
list1[2] = 300
print(list1)
# 添加元素
list1.append(200)
list1.insert(1, 400)
list1 += [1000, 2000]
print(list1)
print(len(list1))
# 删除元素
list1.remove(3)
if 1234 in list1:
list1.remove(1234)
del list1[0]
print(list1)
# 清空列表元素
list1.clear()
print(list1)

列表的生成式语法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import sys

def main():
f = [x for x in range(1, 10)]
print(f)
f = [x + y for x in 'ABCDE' for y in '1234567']
print(f)
# 用列表的生成表达式语法创建列表容器
# 用这种语法创建列表之后元素已经准备就绪所以需要耗费较多的内存空间
f = [x ** 2 for x in range(1, 1000)]
print(sys.getsizeof(f)) # 查看对象占用内存的字节数
print(f)
# 请注意下面的代码创建的不是一个列表而是一个生成器对象
# 通过生成器可以获取到数据但它不占用额外的空间存储数据
# 每次需要数据的时候就通过内部的运算得到数据(需要花费额外的时间)
f = (x ** 2 for x in range(1, 1000))
print(sys.getsizeof(f)) # 相比生成式生成器不占用存储数据的空间
print(f)
for val in f:
print(val)

tuple

类似cpp中结构体

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
def main():
# 定义元组
t = ('骆昊', 38, True, '四川成都')
print(t)
# 获取元组中的元素
print(t[0])
print(t[3])
# 遍历元组中的值
for member in t:
print(member)
# 重新给元组赋值
# t[0] = '王大锤' # TypeError
# 变量t重新引用了新的元组原来的元组将被垃圾回收
t = ('王大锤', 20, True, '云南昆明')
print(t)
# 将元组转换成列表
person = list(t)
print(person)
# 列表是可以修改它的元素的
person[0] = '李小龙'
person[1] = 25
print(person)
# 将列表转换成元组
fruits_list = ['apple', 'banana', 'orange']
fruits_tuple = tuple(fruits_list)
print(fruits_tuple)

dict

类似cpp中unordered_map

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
def main():
scores = {'骆昊': 95, '白元芳': 78, '狄仁杰': 82}
# 通过键可以获取字典中对应的值
print(scores['骆昊'])
print(scores['狄仁杰'])
# 对字典进行遍历(遍历的其实是键再通过键取对应的值)
for elem in scores:
print('%s\t--->\t%d' % (elem, scores[elem]))
# 更新字典中的元素
scores['白元芳'] = 65
scores['诸葛王朗'] = 71
scores.update(冷面=67, 方启鹤=85)
print(scores)
if '武则天' in scores:
print(scores['武则天'])
print(scores.get('武则天'))
# get方法也是通过键获取对应的值但是可以设置默认值
print(scores.get('武则天', 60))
# 删除字典中的元素
print(scores.popitem())
print(scores.popitem())
print(scores.pop('骆昊', 100))
# 清空字典
scores.clear()
print(scores)

文件读写

操作模式 具体含义
'r' 读取 (默认)
'w' 写入(会先截断之前的内容)
'x' 写入,如果文件已经存在会产生异常
'a' 追加,将内容写入到已有文件的末尾
'b' 二进制模式
't' 文本模式(默认)
'+' 更新(既可以读又可以写)

读写txt

read()

1
2
3
f = open('123.txt', 'r', encoding='utf-8')
print(f.read())
f.close()

如果open函数指定的文件并不存在或者无法打开,那么将引发异常状况导致程序崩溃。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def main():
f = None
try:
f = open('123.txt', 'r', encoding='utf-8')
print(f.read())
except FileNotFoundError:
print('无法打开指定的文件!')
except LookupError:
print('指定了未知的编码!')
except UnicodeDecodeError:
print('读取文件时解码错误!')
finally:
if f:
f.close()

上面的案例使用finally语句来释放外部资源的操作;如果不愿意在finally代码块中关闭文件对象释放资源,也可以使用上下文语法,通过with关键字指定文件对象的上下文环境并在离开上下文环境时自动释放文件资源。

1
2
3
4
5
6
7
8
9
10
def main():
try:
with open('123.txt', 'r', encoding='utf-8') as f:
print(f.read())
except FileNotFoundError:
print('无法打开指定的文件!')
except LookupError:
print('指定了未知的编码!')
except UnicodeDecodeError:
print('读取文件时解码错误!')

readline()

1
2
3
4
5
6
7
8
9
10
with open('123.txt', mode='r') as f:
for line in f:
print(line, end='')
time.sleep(0.5)
print()

# 读取文件按行读取到列表中
with open('致橡树.txt') as f:
lines = f.readlines()
print(lines)

读写csv

1
2
3
4
5
6
import csv
# 读取csv文件
with open("test.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
print(row)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import csv

row = ['7', 'hanmeimei', '23', '81', '78', '78']
out = open("test.csv", "a")
csv_writer = csv.writer(out, dialect = "excel")
csv_writer.writerow(row)


# 打开文件,指定写入模式
with open('data.csv', 'w', newline='') as file:
# 创建csv写入对象
writer = csv.writer(file)
# 写入表头
writer.writerow(['姓名', '年龄', '性别'])
# 写入数据
writer.writerows(data)

读写npy

在使用numpy科学计算时,我们想保存一些矩阵和数组数据。但维度较大,有三维,四维甚至五维。此时上述方法对数据的读写就很麻烦。numpy提供了较方便保存数组和矩阵的函数.

  • 使用save和load函数保存和加载数组
1
2
3
4
import numpy as np
x = np.array([1,2,3])
np.save('save',x)
x = np.load('save.npy')
  • 文本格式读写
    numpy还提供了文本保存格式函数savetxt,不同于二进制格式,文本文件可以直接打开查看内容
    但是savetxt方法无法保存三维及以上的数组。此时可以对数组先降维,加载后再升维。
1
2
3
4
5
6
7
import numpy as np
x = np.ones([1,2,3,4]) #四维数组无法直接保存为txt文件
y = x.flatten()
np.savetxt('save.txt')

r = np.load('save.txt')
x = np.reshape(r,(1,2,3,4))

读写xlsx/xls

  • xlrd & xlwt

  • openpyxl

读写json

  • dump - 将Python对象按照JSON格式序列化到文件中
  • dumps - 将Python对象处理成JSON格式的字符串
  • load - 将文件中的JSON数据反序列化成对象
  • loads - 将字符串的内容反序列化成Python对象
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import json


def main():
mydict = {
'name': '骆昊',
'age': 38,
'qq': 957658,
'friends': ['王大锤', '白元芳'],
'cars': [
{'brand': 'BYD', 'max_speed': 180},
{'brand': 'Audi', 'max_speed': 280},
{'brand': 'Benz', 'max_speed': 320}
]
}
try:
with open('data.json', 'w', encoding='utf-8') as fs:
json.dump(mydict, fs)
except IOError as e:
print(e)
print('保存数据完成!')
您的支持将鼓励我继续创作!