此篇是作者(一个萌新)在学习Python3的一点回顾和总结(适合有java或c基础的读者观看)
条件控制
- if 语句
- 基本
if True == 1:
print("hehe")
- 双向
if True == 2:
print("hehe")
else:
print("haha")
- 多路
if True == 2:
print("hehe")
elif False == -1:
print("haha")
else:
print("hoho")
- if 嵌套
if True == 2:
print("hehe")
if 1 > 2:
print("gege")
elif 2 > 3:
print("gogo")
else:
print("gaga")
elif False == -1:
print("hoho")
else:
print("haha")
循环语句
- for循环
for i in [1,2,3,4]:
print(i)
- range函数
for i in range(2,5,1):
print(i) # range()生成一个从2开始到5步长为1的一个算头不算尾的数字序列
- break, continue, pass:前两个与java中的一样,pass表示略过,用于占位
x = ['tom', 'jack']
for i in x:
pass
print(i)
- while循环(在Python中不存在do……while)
n = 5
while n >0:
print(n)
n = n - 1
else:
print('n为零')
异常
- 正常异常处理
try:
number = int(input("请输入一个数字"))
ret = 1/number
print("计算结果是:{0}".format(ret))
except:
print("输入错误")
finally:
print("希望您每天开开心心")
- 用户手动引发
try:
raise NameError # 产生异常,不会继续往下运行
number = int(input("请输入一个数字"))
ret = 1/number
print("计算结果是:{0}".format(ret))
except NameError as e:
print("NameError")
finally:
print("希望您每天开开心心")
迭代器和生成器
- 可迭代:可以用for循环遍历的对象,我们称之为可迭代的对象
for i in "hasdjkhasjkhsjkshd":
print(i)
# 我们可以通过collections模块的Iterable类型来验证该对象是否可迭代
from collections import Iterable
print(isinstance('sdadasdsada', Iterable))
- 迭代器:
- iter()、next()
i = iter("dsajdkhjasjdh")
n = 1
while n:
try:
print(next(i))
except StopIteration as e:
n = 0
- 自定义迭代器
实现了__iter__()与__next__()这两个方法的一个类
- iter():返回一个特殊的迭代器对象
- next():返回下一个迭代器对象
class OuShu:
def __iter__(self):
self.b =0
return self
def __next__(self):
x = self.b
self.b += 2
return x
myclass = OuShu()
myiter = iter(myclass)
mynext = next(myiter)
while mynext < 10:
mynext = next(myiter)
print(mynext)
- 生成器
生成器是一个返回迭代器的函数,生成器就是一个迭代器,使用了yield的函数被称为生成器。
- yield:遇到yield时函数会暂停并保存当前所有的运行信息,返回yield的值,并在下次运行next()方法时从当前位置继续执行
# 斐波那契数列
def fbc(max):
a, b, n = 0, 1, 0
while n < max:
yield b
a, b = b, a+b
n += 1
max = int(input("您需要多少位斐波那契数"))
f = fbc(max)
for i in range(0,max):
print(next(f))
数据结构
- 列表
- 将列表当堆栈使用:用append()将一个元素添加堆栈顶部,用不指定索引pop()将一个元素从堆栈顶释放
- 将列表当队列使用:用append()往队列尾添加元素,用popleft()将队列头删除
- 嵌套列表(多维数组):[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
方法 | 描述 |
list.append(x) | 将x添加到列表末尾 |
list.extend(list) | 将一个列表添加在列表末尾,两个列表的重复元素只保留一个 |
list.insert(a, x) | 将x添加到a位置,其他元素依次后移 |
list.remove(x) | 只将列表的第一个的元素删除 |
list.pop(a) | 将指定a位置的元素删除 |
list.index(x) | 返回x在列表的位置 |
list.clear(list) | 将列表清空,但列表还存在 |
list.count(x) | 返回列表内x元素的个数 |
list.sort(key=none, reverse=False) | 将列表的元素排序,key可以定义为一个函数,reverse有两个选项False和True, False为从大到小,True为从小到大 |
list.reverse() | 反转列表 |
list.copy() | 返回这个列表的副本 |
- 元组(与list类似,但不可修改)
- 只有三个方法
- len():返回元祖长度
- 连接:
tuple0 = (1, 2, 3)
tuple2 = (4, 5, 6)
tuple3 = tuple0 + tuple2
print(tuple3)
- in 查询:
print(1 in (1, 2, 3))
- 集合:可以用set()或大括号创建集合,如果创建空集合必须用set()
- 字典:用{}创建空字典,可以用{key: value, key: value}直接创建或者使用dict([key: value,……])
- 遍历
dicty = {'tom':1, 'jack':2, 'rose':3}
# items得到关键字与对应的值
for k, v in dicty.items():
print(k, v)
# enumerate得到索引位置和对应值
for i, v in enumerate(dicty):
print(i, v)
- 添加、删除元素
d = {}
# 添加,如果字典中存在key=a,那么就会覆盖
d.update(a=2) # 也可以为update({'a': 2})
print(d)
# 删除
d.pop('a') # pop()里为key值
[如果读者没有看懂或者觉得我写的不好可以看官方文档,在此附上链接 ](https://docs.python.org/zh-cn/3/)