切片与迭代

1、切片就是按特定规律取列表或者元组中的某些值

L[start:end:step]表示从L列表的start开始按照step的步长取数,不大等于end(不包括end)

2、tuple和字符串都可以切片,同样也用[]

print('ABCDEFGHIJKLMNOPQRSTUVWXYZ'[::-1])


ZYXWVUTSRQPONMLKJIHGFEDCBA

 字符串[::-1]为将字符串取倒序。 

3、迭代的用法:for a in A,A是一个list或者tuple

dict的迭代要注意到 for a in dict只是迭代到dict的key,如果要迭代dict的value,需要for a in dict.values(),如果需要同时迭代dict的key和value,需要用到for a,b in dict.items()

4、判断一个对象是否可迭代

from collections import Iterable
print(isinstance('abc', Iterable))

5、迭代多个变量

for x,y,z in [[1,2,3],[4,5,6],[7,8,9]]:
print(x,y,z)
输出:

1 2 3
4 5 6
7 8 9

x为1,4,7

6、列表生成式可以简单地描述迭代

 [x的计算式for x in迭代列表 if x的条件]
例如:
[x * x for x in range(1, 11) if x % 2 == 0]
[4, 16, 36, 64, 100]

7、还可以用多层循环得到全排列

例如:

[m + n for m in 'ABC' for n in 'XYZ']
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']

8、课后作业

L1=['Hello','World',18,'Apple',None]
L2=[s.lower() for s in L if isinstance(s,str)==True]
原文地址:https://www.cnblogs.com/vonkimi/p/6828606.html