# python 迭代和列表解析

字符串，列表，元组和字典等对象均支持迭代操作，可用迭代器遍历对象

因为上述对象没有自己的迭代器，iter()函数生成迭代器

d=iter([7,4,3])
for i in range(3):
print(next(d))
next(d)　　　　　　　　越界会报错


d=iter((7,8,(9,0)))
for i in range(3):
print(next(d))

d=iter(('abc'))
for i in range(3):
print(next(d))


d1=iter({'name':'Jhon','age':25})
d2=iter({'name':'Jhon','age':25}.keys())
d3=iter({'name':'Jhon','age':25}.values())
d4=iter({'name':'Jhon','age':25}.items())
for i in range(2):
print(next(d1))
print()

for i in range(2):
print(next(d2))
print()

for i in range(2):
print(next(d3))
print()

for i in range(2):
print(next(d4))
print()

解析

解析就是通过一定的方法来修改

一般和for紧密联系

t=[1,2,3,4]
for x in range(4):
t[x]+=10
for x in range(4):
print(t[x],end=' ')

t=[1,2,3,4]
t=[x+10 for x in t]
for x in range(4):
print(t[x],end=' ')

t=[x+10 for x in range(10) if x%2==0]
for x in range(len(t)):
print(t[x],end=' ')

t=[x+y for x in (10,20) for y in (1,2,3)]
for x in range(len(t)):
print(t[x],end=' ')

t=[x+y for x in (10,20) if x>10 for y in (1,2,3) if y%2==1]
for x in range(len(t)):
print(t[x],end=' ')

t=tuple(x*2 for x in  range(10) if x%2==1)
print(t)

t={x for x in range(10) if x%2==1}
print(t)

t={x:ord(x) for x in 'abcd'}
print(t)

t=[0,2,4,1,3,5]
print(all(t))   #所有对象都为真时返回True
print(any(t))   #有一个对象为真时返回True

t=[0,2,4,1,3,5]
print(sum(t))
print(sorted(t))
print(min(t))
print(max(t))

posted @ 2020-11-02 17:20  Kaiser-  阅读(60)  评论(0编辑  收藏