1. 循环与流程控制
(1) for
myList1 = ["A", "B", "C", "D"]
# 正序遍历
for item in myList1:
print(item)
# 倒序遍历
for item in reversed(myList1):
print(item)
myList2 = list(range(1,5))
# [1, 2, 3, 4]
# 等效于其它语言的for(i=0; i<4; i++)
for index in range(4):
myList2.append(myList1[index])
print(myList2)
# [1, 2, 3, 4, 'A', 'B', 'C', 'D']
# 按索引遍历
for index in range(len(myList2)):
print("索引", index, "对应的元素是:", myList2[index])
for循环本质上是通过不断调用迭代器(Iterator)的next()
函数来实现的:
from collections import Iterable
myList = [3, 6, 9]
for i in myList:
print(i)
# 下面的代码与上面的for循环等效
if isinstance(myList, Iterable):
myIter = iter(myList)
while True:
try:
x = next(myIter)
print(x)
except StopIteration:
break
(2) while
myList = ["A", "B", "C", "D"]
index = 0
while index < len(myList):
print(myList[index])
index += 1
(3) break和continue
myList = list(range(10))
# 循环到5后跳出
index = 0
while True:
print(myList[index])
if index==5:
break
index += 1
# 循环遇到偶数略过,只打印奇数
for item in myList:
if int(item)%2==0:
continue
print(item)
2. 函数
# 定义一个空函数
def voidFun():
pass
# 定义一个求和函数
def getSum(x, y):
if not isinstance(x, (int, float)) and isinstance(y, (int, float)):
raise TypeError("参数'x'和'y'必须为数字")
return x + y
# 定义一个同时返回最大和最小值的函数
def getMinAndMax(x, y, z):
return min(x, y, z), max(x, y, z)
print(voidFun())
# None
print(getSum(3, 5))
# 8
multiValue = getMinAndMax(3, 9, 6)
print(multiValue)
# 多参数返回其实是一个Tuple
# (3, 9)
minValue, maxValue = getMinAndMax(3, 9, 6)
print(minValue, maxValue)
# 3 9
默认参数示例:
def enroll(name, age, sex="male", gold=0, country="China"):
print("name:",name,"\n",
"age:",age,"\n",
"sex:",sex,"\n",
"gold:",gold,"\n",
"country:",country)
enroll("wayne", 23)
# wayne 23 male 0 China
enroll("tina", 19, "female")
# tina 19 female 0 China
enroll("andy", 28, gold=15)
# andy 28 male 15 China
默认参数需要注意的一点是:默认值最好设置为不可变值(例如字符串或数字),否则会带来意料之外的状况:
def addItemToList(myList=[]):
myList.append("End")
print(myList)
# 提供参数连续调用2次是正常的,因为每次是以新的参数值传入
addItemToList([1, 2])
addItemToList([1, 2])
# [1, 2, 'End']
# [1, 2, 'End']
# 当使用默认参数连续调用2次时,第1次已经改变了默认参数指向的List
addItemToList()
addItemToList()
# ['End']
# ['End', 'End']
针对上面的例子,可以修改默认值为None
:
def addItemToList(myList=None):
if myList is None:
myList = []
myList.append("End")
print(myList)
可变参数示例:
def getSum(*numbers):
sum = 0
for i in numbers:
sum += i
print(sum)
return sum
getSum()
# 0
getSum(1, 2, 3)
# 6
myTuple = (1, 3, 5)
getSum(*myTuple)
# 9
关键字参数示例:
def enroll(name, age, **params):
if "gold" in params:
print('传了"gold"这个参数')
print("params:",params)
enroll("wayne", 23, gold=15, sex="male")
# 传了"gold"这个参数
# params: {'gold': 15, 'sex': 'male'}
限制关键字参数必须要以key=value
的形式提供参数,它的定义是以*
分隔:
def enroll(name, age, *, gold, country):
pass
# enroll("wayne", 23, 15, country="China") 未提供关键字将报错
enroll("wayne", 23, gold=15, country="China")
如果函数中间存在一个可变参数,在这个可变参数后面的参数自动会被认定为限制关键字参数:
def enroll(name, age, *skills, gold, country):
pass
# 未提供关键字"gold"将报错
# enroll("wayne", 23, "java", "python", 15, country="China")
enroll("wayne", 23, "java", "python", gold=15, country="China")
3. 生成器(generator)
当创建一个List或Array时,当元素个数越多,则占用的内存就越高;generator能很好的解决内存占用问题,它的特点是边循环边计算,在处理类似斐波拉契数列的场合非常有用。
定义generator和定义函数比较类似,python通过判断是否含有yield
关键字来加以区分:
def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a+b
n = n + 1
for i in fib(10):
print(i)
4. 函数参数
python支持函数参数,示例如下:
def add(x, y):
return x+y
def multiply(x, y):
return x*y
def compute(x, y, fun):
return fun(x, y)
print(compute(2, 5, add))
print(compute(3, 6, multiply))
map
函数可以让一个Iterable里面的每一个元素执行同一个函数:
def square(x):
return x * x
myTuple = tuple(map(square, (2, 4, 6)))
# (4, 16, 36)
myList = list(map(str,[1, 3, 5]))
# ['1', '3', '5']
reduce
函数把一个函数作用在一个序列上,这个函数接收两个参数,reduce
把结果继续和序列的下一个元素做累计计算:
from functools import reduce
def multiply(x, y):
return x*y
result = reduce(multiply, [1, 2, 3, 4])
print(result)
# 24
lambda
表达式提供了一个更加简练的函数式语法来写匿名方法,它的调用形式是lambda argument_list: expression
,argument_list是参数列表,expression是表达式,表达式中出现的参数需要在参数列表中有定义。
用法一:将lambda函数赋值给一个变量,通过这个变量间接调用该lambda函数:
add = lambda x,y:x+y
add(3,5)
用法二:将lambda函数赋值给其他函数,从而将其他函数用该lambda函数替换:
import time
# 屏蔽sleep函数
time.sleep = lambda x:None
time.sleep(10)
print("test")
用法三:将lambda函数作为参数传递给其他函数。
myList = list(map(lambda x: x*x, [2, 3, 4]))
print(myList)
# [4, 9, 16]
filter
函数用于过滤列表,需要实现一个过滤函数:
# 过滤出奇数
def is_odd(n):
return n%2 == 1
myList = list(filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
print(myList)
# [1, 3, 5, 7, 9]
# 过滤出非空字符串
def not_empty(s):
return s and s.strip()
myList = list(filter(not_empty, ['A', '', 'B', None, 'C', ' ']))
print(myList)
# ['A', 'B', 'C']
sorted
函数用于排序,它接收3个参数:列表,key函数,reverse(正向/反向)。调用sorted函数后并不更改原列表,而是返回一个排序后的可循环列表:
# 默认按升序排列,注意字符串是以ASCII码大小来排序的
myList = ["a", "B", "c", "D"]
print(sorted(myList))
# ['B', 'D', 'a', 'c']
# 如果字符串要以"A-Z"的顺序排序,可以先将字母全部转换成大写或小写
myTuple = ("BOY", "apple", "Pig", "monkey")
print(sorted(myTuple, key=str.lower))
# ['apple', 'BOY', 'monkey', 'Pig']
# 按绝对值的倒序排序
myList = [15, 23, -9, 100, -36]
print(sorted(myList, key=abs, reverse=True))
# [100, -36, 23, 15, -9]