给妹子讲python-S01E13循环迭代高级技巧

for x in range(5):
print(x, end=',')

0,1,2,3,4,


range也可以用在任何需要整数列表的地方。直接打印range函数的返回值是不能直接返回一个整数列表的，如果将其作为一个参数传给list函数，则可以一次性显示全部结果。

print(range(5))

range(0, 5)

-

print(list(range(-5,5)))

[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]


S = 'abcdefghijklmn'
for i in range(0,len(S),2):
print(S[i], end=',')

a,c,e,g,i,k,m,


S = 'abcdefghijklmn'
for c in S[::2]:
print(c, end=',')

a,c,e,g,i,k,m,


zip：用来并行迭代多个序列

L1 = [1,2,3,4,5]
L2 = ['A','B','C','D','E']
for t in zip(L1,L2):
print(t, end=',')

(1, 'A'),(2, 'B'),(3, 'C'),(4, 'D'),(5, 'E'),


L1 = [1,2,3,4,5]
L2 = ['A','B','C','D','E']

print(zip(L1,L2))

<zip object at 0x000000000260ED08>


L1 = [1,2,3,4,5]
L2 = ['A','B','C','D','E']
print(list(zip(L1,L2)))

[(1, 'A'), (2, 'B'), (3, 'C'), (4, 'D'), (5, 'E')]


L1 = [1,2,3,4,5]
L2 = ['A','B','C']
print(list(zip(L1,L2)))

[(1, 'A'), (2, 'B'), (3, 'C')]


keys = ['A', 'B', 'C']
vals = [1, 2, 3]
D = dict(zip(keys,vals))
print(D)

{'C': 3, 'A': 1, 'B': 2}


enumerate：用来同时产生偏移和元素

S = 'spam'
for t in enumerate(S):
print(t,end=' ')

(0, 's') (1, 'p') (2, 'a') (3, 'm')


S = 'spam'
print(enumerate(S))

<enumerate object at 0x0000000001ED2558>


【妹子说】这种高级技巧课程的内容还是挺多的，需要多多练习才能好好掌握~

Python爱好者

+ 订阅