python基础教程——切片

获取list或tuple的部分元素:

L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']

L[0:3]
['Michael', 'Sarah', 'Tracy']
L[:3]
['Michael', 'Sarah', 'Tracy']
L[-2:]
['Bob', 'Jack']
L[-2:-1]
['Bob']


L = list(range(100))
L
[0,1,2,3,4,5,...,99]
L[:10:2]
[0,2,4,6,8]
L[::5]
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]
L[:]
[0, 1, 2, 3, ..., 99] //复制一个list

(0,1,2,3)[:3]
(0,1,2)
'ABCDEFG'[:3]
'ABC'
'ABCDEFG'[::2]
'ACEG'

  

posted @ 2017-09-14 22:23  这是你的后会无期  阅读(222)  评论(0编辑  收藏  举报