三:列表的切片与循环
接上一章:
1.列表mylist = [1,2,3,4,5,6,7],请删除第二个(索引值为1)的值 2.删除第二到第五个,索引值为1-4 3.列表mylist = [1,2,3,4,5,6,7,3,2,5,4,2,3,5,55],将列表排序,并去掉重复数据 4.字典dict = {"a":apple,"b":banana,"c":car},去除里面不为水果的元素,并换为"t":tomato
结果:
1.mylist.pop(1) del mylist[1] 2.del mylist[1:4] 3.set(mylist) 4.dict["c"] = "tomato"
从上面引入切片操作:根据索引切片,取出你需要的数据
一:切片
1.切片一般包括:正索引和负索引两部分,如下图所示:
2.切片的一般操作object[start_index:end_index:step],左闭右开
一个完整的切片表达式包含两个“:”冒号,用于分割三个参数(start_index、end_index、step)开始索引,结束索引,步长。
当只有一个“:”冒号时,默认step为1,当一个“:”也没有时,start_index=end_index,表示切取start_index指定的那个元素
step:正负都可,大小决定步长,正负决定取值方向。正往右
start_index:该参数省略时,表示从端点开始取值,step为正从起点,为负从终点
end_index:参数省略表示一直到终点。step为正到终点,为负到起点
3.详细操作
下面所有的list对象都为mylist = [0,1,2,3,4,5,6,7,8,9]为例
1、切取单个元素
mylist[2] ==> 2
mylist[-4] ==> 6
2、切取完整对象
mylist[:]、a[::] ==> [0,1,2,3,4,5,6,7,8,9]
mylist[::-1] 从右往左 ==> [9,8,7,6,5,4,3,2,1,0]
3、start_indexh和end_index全为正索引
mylist[1:6] ==> [1,2,3,4,5]
mylist[1:6:-1] ==> [] 为空
mylist[6:2] ==> []
4、start_index和end_index全为负索引的
mylist[-1:-6] ==> [] step为1,为从左向右,-1:-6为从右到左,所以为空
mylist[-1:-6:-1] ==> [9,8,7,6,5]
5、start_index和end_index正负混搭索引
mylist[1:-6] ==> [1,2,3]
mylist[-1:6:-1] ==> [9,8,7]
6、取偶数位置
mylist[::2] 设置步长为2就行
7、取奇数位置
mylist[1::2] 从1开始,设置步长为2
8.拷贝整个对象
b = mylist[:]
b = mylist.copy()
二:循环语句
python中有for 和while循环两种
1:while的一般形式
while 判断条件(condition):
执行语句(statements)
使用while循环的时候要注意死循环
while True:
pass
使用while的同时可以使用else语句
#!/usr/bin/python3 count = 0 while count < 5: print (count, " 小于 5") count = count + 1 else: print (count, " 大于或等于 5")
2.for语句
for循环可以遍历任何序列的项目,如衣一个列表或者一个字符
for循环的一般格式:
for <variable> in <sequence>: <statements> else: <statements>
实例
#!/usr/bin/python3 sites = ["Baidu", "Google","Runoob","Taobao"] for site in sites: if site == "Runoob": print("hello!") break print("循环 " + site) else: print("没有循环数据!") print("完成循环!")
3.continue和break
continue跳过当前循环进入下一循环,break跳出循环,循环结束
n = 5 while n > 0: n -= 1 if n == 2: break print(n) print('循环结束。') 结果: 4 3 循环结束。
n = 5 while n > 0: n -= 1 if n == 2: continue print(n) print('循环结束。') 结果: 4 3 1 0 循环结束。