1、序列包括列表、字符串和元组
2、列表可以修改,但元组不能修改
>>>edward = ['Edward Gumby',42]
>>>john = ['John Smith',50]
>>>database = [edward,john]
>>>database
[['Edward Gumby',42],['John Smith',50]]
3、序列操作
//索引
>>>greeting = 'Hello'
>>>greeting[0]
'H'
>>>forth = raw_input('Year:')[3]
Year:2005
>>>forth
'5'
//分片
>>>numbers = [1,2,3,4,5,6,7,8,9,10]
>>>numbers[3:6]
[4,5,6]
>>>numbers[7:]
[8,9,10]
>>>numbers[:3]
[1,2,3,4]
>>>numbers[:]
[1,2,3,4,5,6,7,8,9,10]
//步长
>>>numbers[0:10:2]
[1,3,5,7,9]
>>>numbers[8:3:-1]
[9,8,7,6,5]
//序列相加(只有相同类型的序列才能进行连接操作)
>>>[1,2,3]+[4,5,6]
[1,2,3,4,5,6]
>>>'Hello,'+'world!'
'Hello,world!'
//乘法
>>>'H'*5
'HHHHH'
>>>[5]*5
[5,5,5,5,5]
//成员资格
>>>members = 'Hello'
>>>'H' in members
True
>>>'a' in members
False
>>>users = ['mlh','foo','far']
>>>raw_input('Enter your user name:') in users
Enter your user name:mlh
True
//长度、最小值、最大值
>>>numbers = [100,34,678]
>>>len(numbers)
3
>>>max(numbers)
678
>>>min(numbers)
34
//list函数(适用于所有类型的序列)
>>>list('Hello')
['H','e','l','l','o']
//列表操作
//元素赋值
>>>x = [1,1,1]
>>>x[1] = 2
>>>x
[1,2,1]
//删除元素
>>>del x[1]
>>>x
[1,1]
//分片赋值
>>>name = list('Perl')
>>>name
['P','e','r','l']
>>>name[2:] = list('ar')
>>>name
['P','e','a','r']
>>>numbers=[1,5]
>>>numbers[1:1] =[2,3,4]
>>>numbers
[1,2,3,4,5]
//列表方法
//append
>>>lst=[1,2,3]
>>>lst.append(4)
>>>lst
[1,2,3,4]
//count
>>>x=[[1,2],1,1,[2,1,[1,2]]]
>>>x.count(1)
2
>>>x.count([1,2])
1
//extend
>>>a=[1,2,3]
>>>b=[4,5,6]
>>>a.extend(b)
>>>a
[1,2,3,4,5,6]
//index
>>>a=[1,2,3]
>>>a.index('3')
2
>>>a[2]
'3'
//insert
>>>numbers=[1,2,3,5,6,7]
>>>numbers.insert(3.'four')
>>>numbers
[1,2,3,'four',5,6,7]
//pop
>>>x=[1,2,3,4]
>>>x.pop()
4
//remove
>>>x=[1,2,3,4]
>>>x.remove('4')
>>>x
[1,2,3]
//reverse
>>>x=[1,2,3,4]
>>>x.reverse()
>>>x
[4,3,2,1]
//sort
>>>x=[4,6,2,1,7,9]
>>>x.sort()
>>>x
[1,2,4,6,7,9]
//sorted
>>>y = sorted(x)
>>>x
[4,6,2,1,7,9]
>>>y
[1,2,4,6,7,9]
//自定义排序(可以定义cmp函数)
>>>numbers=[5,2,9,7]
>>>numbers.sort(cmp)
>>>numbers
[2,5,7,9]
>>>x=['aardvark'.'avalone','acme','add','aerate']
>>>x.sort(key=len)
>>>x
['add','acme','aerate','avalone','aardvark']
>>>x=[4,6,2,1,7,9]
>>>x.sort(reverse=True)
>>>x
[1,2,4,6,7,9]
4、元组(不可变序列)
>>>1,2,3
(1,2,3)
>>>42,
(42,)
>>>3*(40+2)
126
>>>3*(40+2,)
(42,42,42)
//tuple函数(以一个序列作为参数并将它转换成元组)
>>>tuple([1,2,3])
(1,2,3)
>>>tuple((1,2,3))
(1,2,3)