01切片
基础语法:
List_name[begin_num : end_num : interval ]
返回的是end_num-begin_num个数,但是从begin_num 到end_num-1的元素
小技巧:复制列表:List[:]
注意:tuple也能切片,只是返回的仍然是tuple本身
02迭代
基础语法:
for ... in...
对于list的循环:下标循环
对于dict的循环:
# 对于值的循环:
for v in dict.values():
# 对于键的循环:
for k in dict:
# 二者都循环:
for k,v in dict.items():
*作业代码学习记录
请使用迭代查找一个list中最小和最大值,并返回一个tuple:
#方法一:sorted函数
def findMinAndMax(L):
L = sorted(L)
if L:
return (L[0], L[- 1])
else:
return (None, None)
#方法2:判断是否为空后正常做
def findMinAndMax(x):
if x:
maxValue = minValue = x[0]
for value in x:
if value > maxValue:
maxValue = value
if value < minValue:
minValue = value
return (minValue, maxValue)
else:
return (None, None)
03列表生成器
基本语法:
[ expression_1 for element_1 in list/range if ... ]
[ expression_1 for element_1 in list/range for element_2 in list/range ]
[ expression_1 if... else...for element_1 in list/range ]
小插入:注意循环的层数
L = ['Hello', 'World', 'IBM', 'Apple']
L1= [s.lower() for s in L]
# output:['hello', 'world', 'ibm', 'apple']
Tip:使用内建的isinstance
函数可以判断一个变量是不是字符串
*homework record:
思路一:判断是字符串还是数字,再将生成的list合并
# -*- coding: utf-8 -*-
L1 = ['Hello', 'World', 18, 'Apple', None]
L2 = [x.lower() for x in L1 if isinstance(x,str)]
L3 = [x for x in L1 if isinstance(x,int)]
print(L2)
print(L3)
L4 = L2+ L3
print(L4)
#['hello', 'world', 'apple']
#[18]
#['hello', 'world', 'apple', 18]
思路二:使用if else语句判断
# -*- coding: utf-8 -*-
L1 = ['Hello', 'World', 18, 'Apple', None]
L2 = [x.lower() if isinstance(x,str) else x for x in L1 ]
print(L2)
04生成器
eg1.
# 打印斐波那契数列的前五个数
def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b # 关键语句
a, b = b, a + b
n = n + 1
g=fib(5)
for i in g: # 打印生成器的结果不能用print(g)
print(i)
如果要从第二个给定数字开始打印,则可以用g.next()方法,可以不断调用next函数达到持续输出的效果。
如果要重新给定数字,可以使用g.send( n )方法
理解yield:
有yield,python就会自动将此函数变成generator函数,打上一个标签。这个函数无论有没有return返回值,都是返回一个generator对象。(如果没有返回值,系统默认返回none)
多次调用的generator函数,返回的是多个generator对象
变成generator的函数,在每次调用next()
的时候执行,遇到yield
语句返回,再次执行时从上次返回的yield
语句处继续执行。
*homework record
杨辉三角
def triangles():
x = [1]
yield x
while x:
if len(x) >= 1:
n = len(x)
x = [x[i] if i == 0 or i == n else x[i-1] + x[i] for i in range(n)]
x.append(1)
yield x
05迭代器
凡是可作用于for
循环的对象都是Iterable
类型;
凡是可作用于next()
函数的对象都是Iterator
类型,它们表示一个惰性计算的序列;
注1:惰性计算是只有需要计算下一个数的时候才会开启的计算,所以可以对于一个无限的序列或者集合,但是dic还是list是不可能储存无限个数据的,所以它们不是Iterator。
注2:for循环的本质就是通过调用next()实现的
集合数据类型如list
、dict
、str
等是Iterable
但不是Iterator
,不过可以通过iter()
函数获得一个Iterator
对象。