python 切片操作(slice operation)

提出必要性

对于经常取指定索引范围的操作,用循环十分繁琐,因此,Python提供了切片(Slice)操作符

语法

list[startIndex:endIndex]

例子

# use loop for getting a sublist                                                                                               
L = ['xiaoming', 'xiaohuang', 'xiaoqiang', 'xiaohong', 'xiaogai', 'xiaomei']
n = 3 
r = []
for i in range(n):
    r.append(L[i])

print('original list is: ', L)
print('sublist(3) of list L is: ', r)

print()

# use slice operation for getting a sublist
print('L[0:3] is: ', L[0:3])
print('L[:3] is: ', L[:3])

'''
    use negative index for getting list from reverse order
    negative 1 represents the last element's index
'''
print('L[-2:-1] is: ', L[-2:])

# use a single colon for copying a list
print('L[:] is: ', L[:])

print()

# use slice operation to operate string
S = 'ABCDEFGHIJKL'
print(S[:3])

运行结果

original list is:  ['xiaoming', 'xiaohuang', 'xiaoqiang', 'xiaohong', 'xiaogai', 'xiaomei']
sublist(3) of list L is:  ['xiaoming', 'xiaohuang', 'xiaoqiang']

L[0:3] is:  ['xiaoming', 'xiaohuang', 'xiaoqiang']
L[:3] is:  ['xiaoming', 'xiaohuang', 'xiaoqiang']
L[-2:-1] is:  ['xiaogai', 'xiaomei']
L[:] is:  ['xiaoming', 'xiaohuang', 'xiaoqiang', 'xiaohong', 'xiaogai', 'xiaomei']

ABC
# python  基础 

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×