切片
切片: 去一个list或者tuple的部分元素[起始索引:结束索引:步长]如果是0或者最后一个-1,,可以省略不写
切片不会改变原来的元素,,只是创建一个新元素,,list,tuple,字符串都可以切片
迭代
通过for循环遍历list或者tuple,,这种遍历我们称为迭代iteration
python中不止 list或者 tuple 能迭代,,还有很多可以迭代的对象,,怎么判断他能不能迭代:from Collections.abc import Iterable… 通过判断是不是这个Iterable的实例,,来判断是不是能迭代isinstance(xxx,Iterable)
遍历dict,,,for in直接遍历,dict迭代的是key,,,如果想迭代value,,用for x in dict.values():,既想迭代key,又想迭代value:for key,value in dict.items():
如果list遍历的时候,想拿到遍历时候的索引值,,可以使用enumerate()方法包裹,,
importcollectionsfromtypingimportCollection l=["a","b","c","d","e","f"]# dict 迭代的是keyd={"name":"cc","age":11}forkeyind:print(key,d[key])forvalueind.values():print(value)forkey,valueind.items():print(key,value)fromcollections.abcimportIterableprint(isinstance("abc",Iterable))print(isinstance(123,Iterable))# 把list变成 索引+元素对print(enumerate(l))forkey,valueinenumerate(l):print(key,value)forx,yin[(1,1),(2,3),(3,3),(4,4),(5,5)]:print(x,y)列表生成式
list comprehensions ,,可以用来创建list的生成式
[]: 列表推导式,,立即返回一个列表(): 圆括号是生成器表达式,,返回一个生成器对象,可以迭代,,但是不会立即计算所有值{}: 用于集合推导式,,,或者字典推导式
print([x*xforxinrange(1,2)])foriin(x*xforxinrange(1,11)ifx%2==0):print(i)print(m+nformin'abc'fornin'def')foriin(m+nformin'abc'fornin'def'):print(i)遍历当前目录import os,
importosforiin(dfordinos.listdir(".")):print(i)d={"name":"cc","age":"11"}foriin(k+"="+vfork,vind.items()):print(i)L=['Hello','World','IBM','Apple']print([s.lower()forsinL])print((s.lower()forsinL))