9/22/2008

python中的list----切片

切片 是一个非常有用的概念,其一般形式为 l[start:end:step],其中 start 和 end 分别是开始和结束索引,step 是在切片时要跨过的条目数量。此外,还可以对结束索引使用负值,即从序列的结尾往回计数。另一个有用的功能是以一种很合适的方式处理错误(如超过序列的长度)。
示例code如下:
[coolcode lang="python" linenum="off"]
>>>x=range(10)
>>>x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0] # Get the first item in the list
0
>>>x[5] # Get the sixth item in the list
5
>>> x[1:5] # Get the second through fifth items
[1, 2, 3, 4]
>>>x[0::2] # Get every second item
[0, 2, 4, 6, 8]
>>>x[0], x[1], x[2]
(0, 1, 2)
>>>x[::2]
[0, 2, 4, 6, 8]
>>>x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>x[3::2]
[3, 5, 7, 9]
[/coolcode]

以下示例更为复杂的修改:
[coolcode lang="python" line="off"]
>>>l=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>l[2] = "two" # Change the type of an element
>>>l
[0, 1, 'two', 3, 4, 5, 6, 7, 8, 9]
>>>l[2] = l[2:5] * 2
>>> l
[0, 1, ['two', 3, 4, 'two', 3, 4], 3, 4, 5, 6, 7, 8, 9]
>>> del(l[2]) # Remove single element
>>>l
[0, 1, 3, 4, 5, 6, 7, 8, 9]
>>>l[1:3] = [] # Remove a slice
>>>l
[0, 4, 5, 6, 7, 8, 9]
[/coolcode]

2 评论:

匿名,  2008年11月13日 06:22  

EYqnOP cbcyfnbnhgqy, [url=http://ssarvbszqgmk.com/]ssarvbszqgmk[/url], [link=http://bgkjgvbnjtle.com/]bgkjgvbnjtle[/link], http://mwnbjetsxtpq.com/

匿名,  2008年11月16日 05:50  

cvbwzltgkrgenrctyxjctvaevumrvc

发表评论