1列表操作的进阶
1.1列表的切片
# 列表的切片
names = ['1', '2', '3', '4', '5']
list1 = names[0:3] # 取前三个
list2 = names[:2] # 取前两个
print(list1)
print(list2)
list3 = names[-3:] # 取后三个
list4 = names[2:] # 取后三个
list5 = names[2:4]
print(list3)
print(list4)
print(list5)
1.2遍历列表
# 遍历列表
# for循环遍历列表
names = ['1', '2', '3', '4', '5']
for name in names:
print('hello, ', name)
# for循环遍历切片列表
for name in names[:3]: # 取前三个遍历
print('HELLO, ', name)
1.3复制列表
# 复制列表 (可以是直接复制也可以是切片复制)
names = ['1', '2', '3', '4', '5']
new_list = names
new_list1 = names[:] # 切片复制
print(new_list1)
names[0] = '张三'
print(new_list)
print(new_list1)
这里可以涉及到深拷贝和浅拷贝的概念区别
2二维列表
# 二维列表
import numpy as np # 引入numpy函数
ArrayList = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(ArrayList[0][2]) # 取第一行第三列的值
# ArrayList2 = [[i for i in range(1, 7)]\
# for j in range(1,7) ]
# print(ArrayList2)
newArray = np.array(ArrayList)
# newArrayList = ArrayList[0,:]
newArray2 = newArray[0, :] # 取第一行的所有值
newArray3 = newArray[:, 1] # 取第二列的所有值
print(newArray2)
print(newArray3)
3元组(Tuple)
Python的6种数据类型:
- Number(数字)
- String(字符串)
- List(列表)
- Tuple(元组)
- Set(集合)
- Dictionary (字典)
3.1元组与列表的区别
元组不可改变,不支持赋值
# 元组
names = ('1', '2', '3', '4', '5')
print(names[-1]) # 访问元组的最后一个值
print(names[0:3]) # 访问元组的第一个到第三个值
# 元组的遍历
for name in names:
print('hello, ', name)
for index in range(len(names)):
print('你好, ',names[index])
4if语句
# if语句
grade = 85
if grade == 90:
print('his grade is 90.')
if grade != 90:
print("his grade isn't 90.")
if True:
print('yes')
# 判断
if grade > 90:
print('his grade is more than 90.')
elif grade > 80 and grade <= 90:
print('His grade is 80~90')
else:
print("his grade is less than 90.")
list = [10, 45, 67, 90]
if 30 in list:
print('yes')
else:
print('no')
5文件读取
import matplotlib.pyplot as plt # 导入画图函数
with open('notebook.txt', encoding='utf-8') as file: # 读取文件,“utf-8”是中文格式
# contents = file.read()
# print(contents)
# for line in file:
# print('line:', line) # 逐行输出
contents = file.readlines()
print(contents)
newList = []
for content in contents:
newContent = content.replace('\n', '')
money = newContent.split(':')[-1] # 取最后一个值
newList.append(int(money)) # 将字符串转换为数字,且是整型,若是浮点型此处为float
print(newList)
# 画图
x = [1, 2, 3, 4, 5, 6]
y = newList
plot = plt.plot(x, y, 'r')
plt.xlabel('month')
plt.ylabel('money')
plt.savefig('销售额.png')
plt.legend()
plt.show()
# 求平均值
# 方法一
sum0 = 0
for money in newList:
sum0 += money
average = sum0/len(newList)
print('average:', average)
# 方法二
average2 = sum(newList)/len(newList)
print('avergae2:', average2)
6写入文件
fileName = 'note.txt'
with open(fileName, 'w+') as file:
file.write('11'+'\n') # 换行
file.write('22')
file.seek(0) # 调用seek指向开头
contents = file.read()
print(contents)
7函数
# 求最大值
def maxNum(list):
maxNumber = 0
for num in list:
if num > maxNumber:
maxNumber = num
return maxNumber
age = [22, 20, 19 ,18]
maxAge = maxNum(age)
print(maxAge)
8类
class Dog():
def __init__(self, name, age):
self.name = name
self.age = age
def sit(self):
print(self.name.tittle() + " is now sitting.")
def eat(self, food):
print(self.name.tittle() + " is now eatting." + food)
# 调用类
dog = Dog('Hua', 2) # 实例化
dog.eat('apple')
9类的继承
10字典
# 创建字典
zhangsan = {'name': '张三', 'grade': '高二', 'class': '二班',
'chinese': 99, 'math': 102, 'english': 110,
'hobby': 'basketball'}
# zhangsan = {} # 字典的初始化
# wangwu = dict()
chinese = [100,120,90,98]
print('第二个人的成绩', chinese[1])
print(zhangsan['chinese']) # 读取字典的值
zhangsan['rank_history'] = [10,20,15,20] # 添加列表
zhangsan['rank'] = 20 # 添加字典的值
zhangsan['chinese_detail'] = {'选择':20, '作文':45,
'阅读':20, '其他':14} #添加字典
zhangsan['rank'] = 19 # 字典的修改
del zhangsan['hobby'] # 删除字典的值
print(zhangsan)
# 列表的遍历
for ch in chinese:
print(ch)
# 字典的遍历
for item in sorted(zhangsan): # 按照顺序遍历
print('key:', item)
print('value', zhangsan[item])
print(zhangsan)
print('张三的所有key', zhangsan.keys()) # 遍历的得到所有keys
print('张三的所有value', zhangsan.values()) # 遍历得到所有的values