开始Python -- List和Tuple(1)

时间:2022-01-04 19:36:06

l         Python中最基本的数据结构是SequenceSequence中的每个元素分配一个index来指定位置,index0开始

l         Python6种內建的Sequence,这里聚焦两种最通用的:ListTuple;它们的主要区别是:你可以改变List,但不能改变Tuple

l         List的形式:“,”分割,“[]”包括起来

>>> edward = ['Edward Gumby', 42]

l         List可以嵌套:

>>> john = ['John Smith', 50]

>>> database = [edward, john]

>>> database

[['Edward Gumby', 42], ['John Smith', 50]]

 

1、通用Sequence操作

1) 索引

l         Sequence中的元素从0开始索引:

>>> greeting = 'Hello'

>>> greeting[0]

'H'

l         String是字符Sequence

l         如果使用负数index,则从右边开始索引(最右边为-1):

>>> greeting[-1]

'o'

l         如果函数的返回值是List,可以直接索引:

>>> fourth = raw_input('Year: ')[3]

Year: 2005

>>> fourth

'5'

2Slice

l         指定两个index值来访问Sequence中指定范围的元素(包括开始的元素,但不包括结束的元素):

>>> tag = '<a href="http://www.python.org">Python web site</a>'

>>> tag[9:30]

'http://www.python.org'

>>> tag[32:-4]

'Python web site'                                  

>>> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

>>> numbers[3:6]

[4, 5, 6]

l         如果Slice持续到Sequence的最后,则可以省略后面的index

>>> numbers[-3:]

[8, 9, 10]

l         这对开始也是一样的:

>>> numbers[:3]

[1, 2, 3]

l         如果两者都省略,则为拷贝整个Sequence

>>> numbers[:]

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

l         步长的使用:

>>> numbers[0:10:2]

[1, 3, 5, 7, 9]

l         步长的使用同样可以使用省略形式:

>>> numbers[::4]

[1, 5, 9]

l         步长不能为0,但可以为负数,这时开始index值必须大于结束index值:

>>> numbers[8:3:-1]

[9, 8, 7, 6, 5]

>>> numbers[10:0:-2]

[10, 8, 6, 4, 2]

>>> numbers[0:10:-2]

[]

>>> numbers[::-2]

[10, 8, 6, 4, 2]

>>> numbers[5::-2]

[6, 4, 2]

>>> numbers[:5:-2]

[10, 8]

3) 连接Sequence

>>> [1, 2, 3] + [4, 5, 6]

[1, 2, 3, 4, 5, 6]

>>> 'Hello, ' + 'world!'

'Hello, world!'

>>> [1, 2, 3] + 'world!'

Traceback (most recent call last):

  File "<interactive input>", line 1, in ?

TypeError: can only concatenate list (not "str") to list

l         连接的Sequence必须类型相同

4) 乘法

>>> 'python' * 5

'pythonpythonpythonpythonpython'

>>> [42] * 10

[42, 42, 42, 42, 42, 42, 42, 42, 42, 42]

l         [](空List)、None(空对象)和初期化

>>> sequence = [None] * 10

>>> sequence

[None, None, None, None, None, None, None, None, None, None]

5) 所属

l         使用in操作符可以检查值是否在Sequence中,返回Boolean

>>> permissions = 'rw'

>>> 'w' in permissions

True

>>> 'x' in permissions

False

>>> users = ['mlh', 'foo', 'bar']

>>> raw_input('Enter your user name: ') in users

Enter your user name: mlh

True

6 lenmaxmin函数

>>> numbers = [100, 34, 678]

>>> len(numbers)

3

>>> max(numbers)

678

>>> min(numbers)

34