Python入门基础
print('Hello,world!')
Hello,world!
b=[1,2,3]
b?
Object `b` not found.
通过?来显示一些关于该对象的概要信息
print?
1.单?显示文档字符串
2.双??显示源代码
%run:在IPython中使用它运行任意的python程序文件
%load:导入一个代码单元
导入:import xx(.py)
二元运算符和比较运算符
5-7
-2
12+21.5
33.5
5<=2
False
is关键词:检查两个引用是否为同一对象
is not:不是相同对象
a=[1,2,3]
b=a
c=list(a)
a is b
True
a is not c
True
条件判断
age=18
if age<20:
print('age is',age)
age is 18
age=16
if age>18:
print('age is',age)
else:
print('未成年')
未成年
age=6
if age>18:
print('age is',age)
elif age>=6:
print('上小学')
else:
print('未成年')
上小学
age = int(input('age:')) #定义age的类型
if age > 18:
print('age is ', age)
elif age > 6:
print('上小学')
else:
print('未成年')
age:12
上小学
循环:
- for…in
- while
names = ['小明','小红','小兰']
for name in names:
print(name)
小明
小红
小兰
#求1+2+3+.....+10
sum = 0
num = [1,2,3,4,5,6,7,8,9,10]
for x in num:
sum = sum+x
print(sum)
55
#range函数——以列表的形式生成数字序列 "顾首不顾尾"
print(list(range(0,10)))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#求1+2+3+....+99
sum = 0
num = range(1,100)
for x in num:
sum=sum+x
print(sum)
4950
while循环——条件满足循环,不满足则退出循环
sum=0
n=0
while n<100:
sum=sum+n
n = n+1
print(sum)
4950
break——退出当前循环
n=1
while n<100:
if n>10:
break
print(n)
n=n+1
print('END')
1
2
3
4
5
6
7
8
9
10
END
continue——结束当前循环,进入下一次循环
n = 1
while n<=10:
n = n+1
if n%2==0:
continue
print(n)
3
5
7
9
11
字典
names = ['小明', '小红', '小兰']
scores = [95,85,58]
print(type(names))
<class 'list'>
#定义字典——(key,value)
d = {'小明':95,'小红':85,'小兰':58}
print(type(d))
d['小红']
<class 'dict'>
85
d['小明']=100
d['小明']
100
d
{'小明': 100, '小红': 85, '小兰': 58}
d['小黄']
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-5-0f6b2112474c> in <module>()
----> 1 d['小黄']
KeyError: '小黄'
1.通过in判断key是否存在
'小红' in d
True
'小黄' in d
False
2.通过get方法,如果不存在,返回None,或者是自己指定的值
d.get('小明',-1)
100
#若key值存在则输出value值,若key值不存在,则返回指定值(-1)
d.get('小黄',-1)
-1
如果要删除一个key,可以使用pop(key)方法,对应value也会从dict中删除
d.pop('小明')
100
d
{'小红': 85, '小兰': 58}
注:字典中的key必须是不可变对象
集合
无序、且元素唯一
set([2,2,2,1,3,3])
{1, 2, 3}
{2,2,2,1,3,3}
{1, 2, 3}
集合的操作
a={1,2,3,4,5}
b={3,4,5,6,7,8}
#并集——通过union方法/或者操作符|
a.union(b)
{1, 2, 3, 4, 5, 6, 7, 8}
a | b
{1, 2, 3, 4, 5, 6, 7, 8}
#交集——通过intersection方法 或者 &
a.intersection(b)
{3, 4, 5}
a & b
{3, 4, 5}
#添加
a.add(11)
a
{1, 2, 3, 4, 5, 11}
#移除
a.remove(11)
a
{1, 2, 3, 4, 5}
#置空
a.clear()
a
set()
a={1,2,3,4,5}
c=a.copy()
c
{1, 2, 3, 4, 5}
c |=b #将c中的内容设置为c和b的并集
c
{1, 2, 3, 4, 5, 6, 7, 8}
d=a.copy()
d
{1, 2, 3, 4, 5}
d &= b #将d中的内容设置为d和b的交集
d
{3, 4, 5}
注:和字典类似,集合的元素必须是不可变的
#当且仅当两个集合的内容一模一样时,两个集合才相等
{1,2,3}=={3,2,1}
True
函数
函数声明def
返回 return
def my_function(x,y,z=1.5):
if z>1:
return z*(x+y)
else:
return z/(x+y)
my_function(5,6,z=0.7)
0.06363636363636363
my_function(3.14,7,3.5)
35.49
my_function(10,20)
45.0
#每个函数都可以有位置参数和关键字参数——x,y是位置参数、z是关键字参数
my_function(x=5,y=6,z=7) #有助于代码可读性
77
圆的面积: s = π r 2 s=\pi{r^2} s=πr2
PI = 3.14159
def yuan_mianji(r):
return PI*r*r
yuan_mianji(3)
28.274309999999996
def aa():
pass #什么都不做——一般用作占位语句
aa()
返回多个值
def f():
a=5
b=6
c=7
return a,b,c
a,b,c = f()
f() #实质上是返回了一个对象,也就是元组
(5, 6, 7)
import math
def move(x, y, step, angle=0):
nx = x+step*math.cos(angle)
ny = y-step*math.sin(angle)
return nx, ny
move(10,10,60,30)
(19.25508699325504, 69.2818974455717)
r = move(10,10,60,30) #返回一个元组
print(type(r))
<class 'tuple'>
x,y = move(10,10,60,30)
print(x,y)
19.25508699325504 69.2818974455717
函数的参数
def power(x):
return x*x
power(5)
25
- 求 x n x^n xn
def power(x,n):
s = 1
while n>0:
n = n-1
s = s*x
return s
power(5,3)
125
默认参数
def power(x,n=3): #默认参数可以简化函数的调用
s = 1
while n>0:
n = n-1
s = s*x
return s
power(5)
125
power(5,3)
125
可变参数
(传入的参数个数可变)
求给定一组数字 a,b,c,…,计算 a 2 + b 2 + c 2 + . . . . a^2+b^2+c^2+.... a2+b2+c2+....
def calc(numbers):
sum = 0
for n in numbers:
sum = sum + n*n
return sum
a=[1,2,3,4,5]
calc(a)
55
b=[1,2,3,4,5,6,7,8,9]
calc(b)
285
关键字参数
关键字参数允许传入0个或者任意个含参数名的参数,这些关键字参数在函数内部自动组装成为一个dict
def person(name,age,**kw): # 参数组合时,关键字参数前要加两个星号说明它是一个关键字参数(dict)
print('name:',name,'age:',age,'other:',kw)
person('小明',18)
name: 小明 age: 18 other: {}
person('小明',18,city='兰州')
name: 小明 age: 18 other: {'city': '兰州'}
person('小明',18,city='兰州',job='老师',sex='男')
name: 小明 age: 18 other: {'city': '兰州', 'job': '老师', 'sex': '男'}
extra={'city':'兰州','job':'老师','sex':'男'}
person('小明',18,**extra)
name: 小明 age: 18 other: {'city': '兰州', 'job': '老师', 'sex': '男'}
参数组合
参数定义的顺序必须是:必选参数、默认参数、可变参数、关键字参数
def f1(a,b,c=0,*args,**kw):
print('a=',a,'b=',b,'c=',c,'args=',args,'kw=',kw)
def f2(a,b,c=0,*,d,**kw):
print('a=',a,'b=',b,'c=',c,'d=',d,'kw=',kw)
f1(1,2)
a= 1 b= 2 c= 0 args= () kw= {}
f1(1,2,c=3)
a= 1 b= 2 c= 3 args= () kw= {}
f1(1,2,3,'a','b')
a= 1 b= 2 c= 3 args= ('a', 'b') kw= {}
f1(1,2,3,'a','b',x=100)
a= 1 b= 2 c= 3 args= ('a', 'b') kw= {'x': 100}
f2(1,2,d=99,ext=None)
a= 1 b= 2 c= 0 d= 99 kw= {'ext': None}
args = (1, 2, 3, 4)
kw = {'d': 99, 'x': '#'}
f1(*args, **kw)
a= 1 b= 2 c= 3 args= (4,) kw= {'d': 99, 'x': '#'}
args = (1, 2, 3)
f2(*args, **kw)
a= 1 b= 2 c= 3 d= 99 kw= {'x': '#'}
函数参数的注意点:
- 默认参数一定是不可变对象
- 可变参数(*)和关键字参数(**)的语法
- 可变参数接受的是一个tuple/list,e.g. func((1,2,3))
- 关键字参数接受的是一个dict , func(**{‘a’:1,‘b’:2})
递归函数
求阶乘 n ! = 1 ∗ 2 ∗ 3 ∗ . . . . ∗ n n!=1*2*3*....*n n!=1∗2∗3∗....∗n
阶乘函数可以定义为 f a c t ( n ) = n ∗ f a c t ( n − 1 ) fact(n) = n*fact(n-1) fact(n)=n∗fact(n−1)
def fact(n):
if n == 1:
return 1
return n*fact(n-1)
fact(10)
3628800
fact(50)
30414093201713378043612608166064768844377641568960512000000000000
fact(5000) #溢出
---------------------------------------------------------------------------
RecursionError Traceback (most recent call last)
<ipython-input-49-6fb59674a4c5> in <module>()
----> 1 fact(5000)
<ipython-input-46-64f76ad885b7> in fact(n)
2 if n == 1:
3 return 1
----> 4 return n*fact(n-1)
... last 1 frames repeated, from the frame below ...
<ipython-input-46-64f76ad885b7> in fact(n)
2 if n == 1:
3 return 1
----> 4 return n*fact(n-1)
RecursionError: maximum recursion depth exceeded in comparison
注意使用递归函数时需要注意防止栈(stack)溢出
尾递归的定义很简洁: 递归语句是函数的最后一条语句
操作系统使用堆栈来处理递归,对于一般的递归,操作系统要在堆栈上新建一个栈帧来存储当前调用函数的数据,比如局部变量、现场信息、返回地址等。每递归一次就新建一个栈帧,压到栈顶。如果处理很深的递归或函数处理数据很大时,很有可能造成栈溢出。
解决方案:尾递归优化:return语句不包含表达式
而对于尾递归,编译器会作出一些优化。即若编译器发现这次递归是尾递归,它不会去新建一个栈帧,而是用当前函数的信息覆盖掉栈顶栈帧中的信息。之所以能这么做是因为递归语句位于函数的最后,前面的计算工作都已经完成了,不用保存中间结果。这样一来省去了创建栈帧的开销;二来避免了栈溢出。
def fact_tail(num,a): #尾递归函数
if num==1:
return a
return fact_tail(num-1,num*a)
import time
t1 = time.time()
fact(2000)
t2 = time.time()
t = t2 - t1
print(t1,t2,t)
1611302856.666621 1611302856.6766376 0.010016679763793945
fact_tail(2000,1)
331627509245063324117539338057632403828111720810578039457193543706038077905600822400273230859732592255402352941225834109258084817415293796131386633526343688905634058556163940605117252571870647856393544045405243957467037674108722970434684158343752431580877533645127487995436859247408032408946561507233250652797655757179671536718689359056112815871601717232657156110004214012420433842573712700175883547796899921283528996665853405579854903657366350133386550401172012152635488038268152152246920995206031564418565480675946497051552288205234899995726450814065536678969532101467622671332026831552205194494461618239275204026529722631502574752048296064750927394165856283531779574482876314596450373991327334177263608852490093506621610144459709412707821313732563831572302019949914958316470942774473870327985549674298608839376326824152478834387469595829257740574539837501585815468136294217949972399813599481016556563876034227312912250384709872909626622461971076605931550201895135583165357871492290916779049702247094611937607785165110684432255905648736266530377384650390788049524600712549402614566072254136302754913671583406097831074945282217490781347709693241556111339828051358600690594619965257310741177081519922564516778571458056602185654760952377463016679422488444485798349801548032620829890965857381751888619376692828279888453584639896594213952984465291092009103710046149449915828588050761867924946385180879874512891408019340074625920057098729578599643650655895612410231018690556060308783629110505601245908998383410799367902052076858669183477906558544700148692656924631933337612428097420067172846361939249698628468719993450393889367270487127172734561700354867477509102955523953547941107421913301356819541091941462766417542161587625262858089801222443890248677182054959415751991701271767571787495861619665931878855141835782092601482071777331735396034304969082070589958701381980813035590160762908388574561288217698136182483576739218303118414719133986892842344000779246691209766731651433494437473235636572048844478331854941693030124531676232745367879322847473824485092283139952509732505979127031047683601481191102229253372697693823670057565612400290576043852852902937606479533458179666123839605262549107186663869354766108455046198102084050635827676526589492393249519685954171672419329530683673495544004586359838161043059449826627530605423580755894108278880427825951089880635410567917950974017780688782869810219010900148352061688883720250310665922068601483649830532782088263536558043605686781284169217133047141176312175895777122637584753123517230990549829210134687304205898014418063875382664169897704237759406280877253702265426530580862379301422675821187143502918637636340300173251818262076039747369595202642632364145446851113427202150458383851010136941313034856221916631623892632765815355011276307825059969158824533457435437863683173730673296589355199694458236873508830278657700879749889992343555566240682834763784685183844973648873952475103224222110561201295829657191368108693825475764118886879346725191246192151144738836269591643672490071653428228152661247800463922544945170363723627940757784542091048305461656190622174286981602973324046520201992813854882681951007282869701070737500927666487502174775372742351508748246720274170031581122805896178122160747437947510950620938556674581252518376682157712807861499255876132352950422346387878954850885764466136290394127665978044202092281337987115900896264878942413210454925003566670632909441579372986743421470507213588932019580723064781498429522595589012754823971773325722910325760929790733299545056388362640474650245080809469116072632087494143973000704111418595530278827357654819182002449697761111346318195282761590964189790958117338627206088910432945244978535147014112442143055486089639578378347325323595763291438925288393986256273242862775563140463830389168421633113445636309571965978466338551492316196335675355138403425804162919837822266909521770153175338730284610841886554138329171951332117895728541662084823682817932512931237521541926970269703299477643823386483008871530373405666383868294088487730721762268849023084934661194260180272613802108005078215741006054848201347859578102770707780655512772540501674332396066253216415004808772403047611929032210154385353138685538486425570790795341176519571188683739880683895792743749683498142923292196309777090143936843655333359307820181312993455024206044563340578606962471961505603394899523321800434359967256623927196435402872055475012079854331970674797313126813523653744085662263206768837585132782896252333284341812977624697079543436003492343159239674763638912115285406657783646213911247447051255226342701239527018127045491648045932248108858674600952306793175967755581011679940005249806303763141344412269037034987355799916009259248075052485541568266281760815446308305406677412630124441864204108373119093130001154470560277773724378067188899770851056727276781247198832857695844217588895160467868204810010047816462358220838532488134270834079868486632162720208823308727819085378845469131556021728873121907393965209260229101477527080930865364979858554010577450279289814603688431821508637246216967872282169347370599286277112447690920902988320166830170273420259765671709863311216349502171264426827119650264054228231759630874475301847194095524263411498469508073390080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
切片
对于list或者tuple会有取部分元素的操作
L=['小明','小红','小华','小黄']
type(L)
list
L[0]
'小明'
L[1]
'小红'
L[2]
'小华'
L[3]
'小黄'
L[-1]
'小黄'
L[-2]
'小华'
[L[0],L[1],L[2]]
['小明', '小红', '小华']
range(3)
range(0, 3)
# 取前n个元素,也就是索引为 0~(n-1)的元素。
r = []
n = 3
for i in range(n):
r.append(L[i]) #append方法:将元素添加到尾部
r
['小明', '小红', '小华']
L
['小明', '小红', '小华', '小黄']
#切片——顾头不顾尾
L[:3]
['小明', '小红', '小华']
L[0:3]
['小明', '小红', '小华']
L[-1]
'小黄'
L[1:]
['小红', '小华', '小黄']
L[-4:]
['小明', '小红', '小华', '小黄']
L[-4:-1]
['小明', '小红', '小华']
L = list(range(100))
L
[0,
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,
38,
39,
40,
41,
42,
43,
44,
45,
46,
47,
48,
49,
50,
51,
52,
53,
54,
55,
56,
57,
58,
59,
60,
61,
62,
63,
64,
65,
66,
67,
68,
69,
70,
71,
72,
73,
74,
75,
76,
77,
78,
79,
80,
81,
82,
83,
84,
85,
86,
87,
88,
89,
90,
91,
92,
93,
94,
95,
96,
97,
98,
99]
L[:10]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
L[-10:]
[90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
L[10:20]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
L[:10:2] #从0开始取到10截止(不包括10),每隔两个数取一个值
[0, 2, 4, 6, 8]
L[::5] #步进值step在第二个冒号后使用,每个多少个数取一个值
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]
L[::-1] #步进值为-1时可将列表或元组翻转
[99,
98,
97,
96,
95,
94,
93,
92,
91,
90,
89,
88,
87,
86,
85,
84,
83,
82,
81,
80,
79,
78,
77,
76,
75,
74,
73,
72,
71,
70,
69,
68,
67,
66,
65,
64,
63,
62,
61,
60,
59,
58,
57,
56,
55,
54,
53,
52,
51,
50,
49,
48,
47,
46,
45,
44,
43,
42,
41,
40,
39,
38,
37,
36,
35,
34,
33,
32,
31,
30,
29,
28,
27,
26,
25,
24,
23,
22,
21,
20,
19,
18,
17,
16,
15,
14,
13,
12,
11,
10,
9,
8,
7,
6,
5,
4,
3,
2,
1,
0]
tuple 和 list 的区别:
tuple也是一种list,唯一的区别是tuple不可变
T=(1,2,3,4)
T
(1, 2, 3, 4)
type(T)
tuple
T[:3] #切片的特点:顾首不顾尾(不包含尾部)
(1, 2, 3)
S='abcdefgh'
S
'abcdefgh'
type(S)
str
S[:3]
'abc'
迭代
更替
每一次对过程的重复称为一次“迭代”,而每一次迭代得到的结果会作为下一次迭代的初始值。
d = {'a':1,'b':2,'c':3}
d
{'a': 1, 'b': 2, 'c': 3}
for key in d:
print(key)
a
b
c
for value in d.values():
print(value)
1
2
3
d.items()
dict_items([('a', 1), ('b', 2), ('c', 3)])
for key,value in d.items():
print(key,value)
a 1
b 2
c 3
for ch in 'ABCD':
print(ch)
A
B
C
D
通过collections模块的Iterable类型判断一个对象是否可以迭代的
from collections import Iterable
isinstance('abc',Iterable) # 字符串
True
isinstance(('a','b','c'),Iterable) # tuple
True
isinstance({'a':1,'b':2,'c':3},Iterable) # dict
True
isinstance(['a','b','c'],Iterable) # list
True
isinstance(123,Iterable)
False
# 常用写法1
for i,value in enumerate(['a','b','c']):
print(i,value)
0 a
1 b
2 c
# 常用写法2
for x,y in [(1,10),(2,3),(7,2)]:
print(x,y)
1 10
2 3
7 2
列表生成
list(range(0,10)) #range特点:顾首不顾尾
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
如何生成 $[11,22,33,…1010] $ ?
L = []
for x in range(1,11):
L.append(x*x)
L
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[x*x for x in range(1,11)] # 单层循环
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[x*x for x in range(1,11) if x%2==0] # 循环+判断
[4, 16, 36, 64, 100]
[m+n for m in 'ABC' for n in 'XYZ'] # 两层循环
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
# 列出当前目录下的所有文件和目录名(常用方法***)
import os
[d for d in os.listdir('.')]
['.anaconda',
'.android',
'.AndroidStudio2.2',
'.BigNox',
'.conda',
'.condarc',
'.eclipse',
'.gradle',
'.ipynb_checkpoints',
'.ipython',
'.jupyter',
'.oracle_jre_usage',
'.p2',
'.packettracer',
'.tooling',
'3D Objects',
'Anaconda',
'AndroidStudioProjects',
'AppData',
'Application Data',
'Cisco Packet Tracer 7.1',
'Contacts',
'Cookies',
'Desktop',
'Documents',
'Downloads',
'eclipse-workspace',
'Favorites',
'Links',
'Local Settings',
'MicrosoftEdgeBackups',
'Music',
'My Documents',
'NetHood',
'Nox_share',
'NTUSER.DAT',
'ntuser.dat.LOG1',
'ntuser.dat.LOG2',
'NTUSER.DAT{008df748-2ae4-11eb-a7dd-d872588d1cf0}.TM.blf',
'NTUSER.DAT{008df748-2ae4-11eb-a7dd-d872588d1cf0}.TMContainer00000000000000000001.regtrans-ms',
'NTUSER.DAT{008df748-2ae4-11eb-a7dd-d872588d1cf0}.TMContainer00000000000000000002.regtrans-ms',
'ntuser.ini',
'OneDrive',
'Pictures',
'PrintHood',
'Python 入门基础.ipynb',
'Recent',
'Saved Games',
'Searches',
'SendTo',
'Templates',
'UIDowner',
'Videos',
'vmlogs',
'wekafiles',
'workspace',
'Yinxiang Biji',
'「开始」菜单']
d = {'x':1,'y':2,'z':3}
[k+'='+str(v) for k,v in d.items()] #items() 函数以列表返回可遍历的(键, 值) 元组数组。
['x=1', 'y=2', 'z=3']
'ABC'.lower() # lower() 方法转换字符串中所有大写字符为小写。
'abc'
L=['Hello','World','Lanzhou','NWNU']
L
['Hello', 'World', 'Lanzhou', 'NWNU']
# 使用列表表达式将L中的所有字符串转换为小写
[s.lower() for s in L]
['hello', 'world', 'lanzhou', 'nwnu']
生成器(generator)
python中一边循环一边计算的机制,称为生成器
创建生成器
- 把列表生成式中的 [] 改成 ()
L = [x*x for x in range(10)]
L
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
g = (x*x for x in range(10))
g
<generator object <genexpr> at 0x0000016C9132D410>
#打印g的值
next(g)
0
next(g)
1
next(g)
4
next(g)
9
next(g)
16
next(g)
25
next(g)
36
next(g)
49
next(g)
64
next(g)
81
g = (x*x for x in range(10))
for n in g:
print(n)
0
1
4
9
16
25
36
49
64
81
def fib(max):
n,a,b=0,0,1
while n<max:
print(b)
# a,b=b,a+b
t=(b,a+b) #(1,2)
a=t[0] # 1
b=t[1] # 2
n=n+1
return 'DONE'
fib(6)
1
1
2
3
5
8
'DONE'
将fib()函数变成生成器,把print(b) 改成 yield b 就可以了
def fib(max):
n,a,b=0,0,1
while n<max:
yield b
a,b=b,a+b
n=n+1
return 'DONE'
for n in fib(6):
print(n)
1
1
2
3
5
8
如果一个函数定义中包含yield关键字,那么这个函数就不是一个普通函数了,而是一个生成器
生成器和函数的执行流程不同。
- 函数是顺序执行,碰到return或者最后一行函数语句则返回
- 生成器函数,每次调用next()执行,遇到yield语句返回,再次执行时从上次返回的yield语句出继续执行
def odd():
print('step 1')
yield 1
print('step 2')
yield 3
print('step 3')
yield 5
o = odd()
next(o)
step 1
1
next(o)
step 2
3
next(o)
step 3
5
迭代器
isinstance()判断一个对象是否是Iterable对象 (可迭代对象)
from collections import Iterable
isinstance([1,2,3],Iterable)
True
可以被next()函数调用并不断返回下一个值得对象称为迭代器 Iterator
from collections import Iterator
isinstance([1,2,3],Iterator)
False
isinstance({},Iterator)
False
isinstance('abc',Iterator)
False
isinstance((x for x in range(10)),Iterator)
True
生成器都是迭代器对象,但是字典、列表、字符串虽然是可迭代对象,但不是迭代器
把字典、列表、字符串 等从Iterable转换成Iterator,可以用iter()
isinstance(iter([1,2,3]),Iterator)
True
isinstance(iter({}),Iterator)
True
isinstance(iter('abc'),Iterator)
True