python List使用
1.enumerate
用在遍历中,返回下标和数据
name_arr = ["shijingjing", "renjiangfeng", "anqi"]
for index, name in enumerate(name_arr):
print("index:%s,name:%s" % (index, name))
print("-----------")
运行结果:
2.slice
b=a[i:j] 表示复制a[i]到a[j-1]
name_arr = ["shijingjing", "renjiangfeng", "anqi"]
print("name_arr:%s" % name_arr)
name_arr_slice = name_arr[1:3]
print("name_arr_slice:%s" % name_arr_slice)
print("------")
运行结果:
当i缺省时,默认是0,即a[:j]表示a[0:j]
当j缺省时,默认是len(a),即a[i:]表示a[i:len(a)]
当i,j都缺省时,表示复制完整列表
name_arr = ["shijingjing", "renjiangfeng", "anqi"]
print("name_arr:%s" % name_arr)
name_arr_slice = name_arr[:2]
print("name_arr_slice:%s" % name_arr_slice)
name_arr_slice2 = name_arr[1:]
print("name_arr_slice2:%s" % name_arr_slice2)
name_arr_slice3 = name_arr[:]
print("name_arr_slice3:%s" % name_arr_slice3)
print("------")
运行结果:
b=a[i:j:s],i,j与上面一样,s表示步长,缺省为1
当s<0时,i缺省时,默认为-1,j缺省时,默认为-len(a)-1
所以a[::-1]表示a[-1:-len(a)-1:-1],复制从最后一个元素到第一个元素
name_arr = ["shijingjing", "renjiangfeng", "anqi"]
print("name_arr:%s" % name_arr)
name_arr_slice = name_arr[::-1]
print("name_arr_slice:%s" % name_arr_slice)
print("------")
运行结果:
3.将a中的偶数挑出*2
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print("a:%s" % a)
b = [x*2 for x in a if x%2==0]
print("b:%s" % b)
print("------")
运行结果: