取出一个list或者tuple的一部分,最笨的方法有:
>>> L = ["python","java","oc","swift"]
>>> x = [L[0],L[1]]
>>> x
['python', 'java']
取出前n个,也可以使用循环的方式:
>>> L = ["python","java","oc","swift"]
>>> n = 3
>>> y = []
>>> for i in range(n):
... y.append(L[i])
...
>>> y
['python', 'java', 'oc']
不过,循环的方式过于复杂。
Python提供了切片操作符,能够大大简化这种操作。
>>> L = ["python","java","oc","swift"]
>>> x = L[0:3]
>>> x
['python', 'java', 'oc']
[m:n]表示从第m个索引开始,到第n个索引结束,不包括第n个索引。例如上面[0:3]:表示从第0个开始,第3个结束,不包括第3个。
也可以不写起始,默认从0开始:
>>> L = ["python","java","oc","swift"]
>>> x = L[:3]
>>> x
['python', 'java', 'oc']
Python支持L[-1]取倒数第一个元素,当然也支持倒数切片。
>>> L
['python', 'java', 'oc', 'swift']
>>> L[-1]
'swift'
倒数切片:
>>> L[-2:]
['oc', 'swift']
>>> L[-1:]
['swift']
>>> L[-2:-1]
['oc']
倒数第一个的索引是-1。
下面是关于切片的其它相关操作:
前10个,逢两个取一个:
>>> L = range(100)
>>> 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]
复制这个list:
>>> X = L[:]
>>> X
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
tuple也是一种list,只是tuple不可变。
tuple也可以切片操作,操作结果仍然是tuple:
>>> (1,2,3,4,5)[:3]
(1, 2, 3)
字符串也可以,操作完仍然是字符串:
>>> "helloworld"[:5]
'hello'