1.列表和元祖的區別:python
列表能夠修改,而元祖不能數據結構
2.通用序列操做:app
2.1.索引函數
1.序列中的索引都是有編號的,從0開始遞增spa
2.字符串就是一個由字符組成的序列 對象
2.2 分片排序
1.分片是爲了提取序列的一部分 索引
2.爲了讓分片包含列表中的最後一個元素,必須提供最後一個元素的下一個元素對應的索引做爲邊界rem
3.>>>number=[1,2,3,4,5,6]字符串
>>>number[0:3]
[1,2,3]
>>>number[5:]
[6]
>>>number[-3:-1]
[4,5]
2.3 序列相加
1.兩種相同類型的序列才能相加
2.>>>[1,2,3]+[4,5,6]
[1,2,3,4,5,6]
>>>'hello,'+'world'
'hello,world'
2.4 序列相乘
初始化序列
>>>a=num[none]*10
[none,none,none,none,none,none,none,none,none,none]
2.5 成員檢查
>>>a='mail'
>>>'m' in a
true
>>>b=['mil','too','huj']
>>>'mil' in b
true
>>>raw_input('enter your name: ') in b
enter your name: mkl
false
2.6 長度,最小值和最大值
1.>>>n=[100,30,40]
>>>len(n)
3
>>>min(n)
30
>>>max(n)
100
2.7.list函數
將字符串拆分紅序列
>>>list(‘hello’)
['h','e','l','l','o']
3.列表的基本操做
3.1元素賦值
>>>A=[1,2,3]
>>>A[1]=3
>>>A
[1,3,3]
3.2 刪除元素
>>>b=['hel','hjk','ee','eeq']
>>>del b[1]
>>>b
['hel','ee','eeq']
3.3 分片賦值
>>>name=list('hello')
>>>name[3:3]=list('hello')
>>>name
‘h’,‘e’,'l','h','e','l','l', 'o','l','o'
4.列表方法
方法:一個與某些對象有緊密聯繫的函數,對象多是列表、數字,也多是字符串或者其餘類型的對象。
4.1append
在列表末尾追加新的對象,只是在恰當的位置修改了原來的列表,並非返回了一個修改過的新列表。
>>>name=[1,2,3,4]
>>>name.append(5)
>>>name
[1,2,3,4,5]
4.2count
統計一個元素在列表中出現的次數
>>>name=[['he','pp'],'pp','pp']
>>>name.count('pp')
>>>name
4.3 extend
能夠在列表的末尾一次性追加另外一個序列中的多個值
>>>a=['a',1,4]
>>>b=['b',1,5]
>>>a.extend(b[0:1])
>>>a
['a', 1, 4, 'b']
4.4index
從列表中找出某個值第一個匹配項的索引值
>>>name=['who','are','you','are','are']
>>>name.index('are')
>>>1
4.5insert
insert方法用於將對象插入到列表中
>>>n = [1,2,3,4,5]
>>>n.insert(3,'four')
>>>n
[1,2,3,'four',4,5]
4.6pop
pop方法會移除列表中的一個元素(默認最後一個),而且返回該元素的值(pop是惟一既能修改列表又能返回元素值(除了none)的列表方法)
>>>x=[1,2,3]
>>>x.pop()
3
>>>x.pop(0)
1
>>>x
2
注:pop方法能夠實現一種常見的數據結構-棧。python沒有入棧的方法,但能夠使用append方法來代替。若是入棧等於出棧的值相等,最後獲得的仍是最後的棧
>>>x=[1,2,3]
>>>x.append(x.pop())
>>>x
[1,2,3]
4.7remove
remove用來移除列表中某個值的第一個匹配項:
>>>x=['aa','bb','aa','cc']
>>>x.remove('aa')
>>>x
['bb','aa','cc']
4.8reverse
reverse方法將列表中的元素反向的存放
>>>x=[1,2,3]
>>>x.reverse()
>>>x
[3,2,1]
4.9sort
sort用於在原位置對列表進行排序。在原位置排序意味着改變了原來的列表,從而讓其中的元素能按照必定的順序排列,而不是返回一個已排序的列表副本。
如:
x=[1,3,2]
print(x,x.sort())
----------
[1,2,3] none
4.10 compare(x,y)
5.元祖
5.1建立元祖:用逗號隔開一些值,或者用圓括號括起來的值
>>>1,2,3
(1,2,3)
>>>(1,2,3)
(1,2,3)