1.1   切片

listtuple中的部分元素是非常常见的操作。

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

>>> [L[0], L[1], L[2]]      --很普通的办法

['Michael', 'Sarah', 'Tracy']

>>> l = []

>>> n = 3

>>> for i in range(3):      --使用循环

...    l.append(L[i])

...

>>> l

['Michael', 'Sarah', 'Tracy']

切片操作

>>> L

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

>>>

>>>

>>>

>>> L[0:3]                --从索引0位置开始取3

['Michael', 'Sarah', 'Tracy']

>>> L[1:4]                 --从索引1位置开始取3   

['Sarah', 'Tracy', 'Bob']

>>> L[:]                   --取的全部

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

>>>L[-1:]                 --默认从倒数第一个位置取到最后

['Jack']

>>>L[-3:-1]               --从倒数第三个位置取到倒数第一个位置,共计2

['Tracy', 'Bob']

>>> L[-1:2]                --list

[]

>>> L[:4]                  --默认从顺数第一个位置取到第四个位置,共计4

['Michael', 'Sarah', 'Tracy', 'Bob']

 

>>> L= list(range(100))

>>> L

[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]

>>> L[:10]                 --取前10

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> L[-10:]                --取后10

[90, 91, 92, 93, 94, 95, 96, 97, 98, 99]

>>> L[10:20]

[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

>>> L[10:20:2]             --取第10个到第20个,没两个取一个

[10, 12, 14, 16, 18]

>>> L[::5]                 --所有元素中每5个取一个

[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50,55, 60, 65, 70, 75, 80, 85, 90, 95]

Tuple的切片操作

>>> (1, 2, 3, 4, 5)[::2]

(1, 3, 5)

>>> (1, 2, 3, 4, 5)[:2]

(1, 2)

字符串的切片操作

>>> 'abcdef'[:2]

'ab'

>>> 'abcdef'[-4::2]

'ce'

切片后,仍然是字符串

Python没有针对字符串的截取函数,只需要切片一个操作就可以完成,非常简单。