1.列表操作
1.賦值
>>>ll = ['2', 'hello', 8.9, ['hahhah', 2]]
>>> list_from_other = list('Hello Wrold!')
>>> list_from_other
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'r', 'o', 'l', 'd', '!']
2.訪問
>>> ll[0]
'2'
>>> ll[3]
['hahhah', 2]
>>> ll[3][0]
'hahhah'
>>> ll[-3:-1]
['hello', 8.9]
3.更新
>>> ll[0]=1234567890
>>> ll
[1234567890, 'hello', 8.9, ['hahhah', 2]]
>>> ll.append('This is a test!')
>>> ll
[1234567890, 'hello', 8.9, ['hahhah', 2], 'This is a test!']
>>> l = ['string', 's', 56]
>>> ll.extend(l)
>>> ll
[1234567890, 'hello', 8.9, ['hahhah', 2], 'This is a test!', 'string', 's', 56]
4.刪除
>>> del ll[1]
>>> ll
[1234567890, 8.9, ['hahhah', 2], 'This is a test!', 'string', 's', 56]
>>> ll.remove('This is a test!')
>>> ll
[1234567890, 8.9, ['hahhah', 2], 'string', 's', 56]
>>> ll.pop(2)
['hahhah', 2]
>>> ll
[1234567890, 8.9, 'string', 's', 56]
>>> ll.pop()
56
2.序列類型可用的內建函數(shù)
>>> alist = [100, 3, 0, 34, 98, 33, 0.3, 54, 23]
1.迭代
>>> for item in alist: #遍歷元素
print item
100
3
0
34
98
33
0.3
54
>>> for i in range(len(alist)): #對每個元素進行操作
alist[i] * 2
200
6
0
68
196
66
0.6
108
>>> for index, value in enumerate(alist): #同時返回index和list中的元素
print index, value
0 100
1 3
2 0
3 34
4 98
5 33
6 0.3
7 54
8 23
>>> for i, j in zip(ll, l): #zip()參數(shù)可以是dict或tuple,同時輸出多個,以最短的為主
print i, j
1234567890 string
8.9 s
string 56
2.len()返回List長度
>>> print len(alist)
9
3.返回List中最大的元素
>>> max(alist)
100
4.返回List中最小的元素
>>> min(alist)
0
5.返回List中元素的和盾碗,只有List全部是數(shù)字才可以
>>> sum(alist)
345.3
6.sorted()方法返回排序號的序列,有字母時按照ASCⅡ碼排序
>>> print sorted(alist)
[0, 0.3, 3, 23, 33, 34, 54, 98, 100]
7.reversed()方法不返回序列锰镀,返回一個迭代器
>>> print reversed(alist)
<listreverseiterator object at 0x0000000002053B38>
>>> alist
[100, 3, 0, 34, 98, 33, 0.3, 54, 23]
3.序列操作符
>>> alist = [100, 3, 0, 34, 98, 33, 0.3, 54, 23]
1.成員判斷符,'in'或者'not in '
>>> 100 in alist
True
>>> 2 in alist
False
>>> 0 not in alist
False
2.切片'[::]'或者'[:]' slice[n:m]開始的位置包括n,結束在m之前织中,類似左開右閉區(qū)間 [n,m)
>>> alist[::2]
[100, 0, 98, 0.3, 23]
>>> alist[2:5:2]
[0, 98]
>>> alist[::-1]
[23, 54, 0.3, 33, 98, 34, 0, 3, 100]
3.重復操作符'*'
>>> ll = ['2', 'hello', 8.9, ['hahhah', 2]]
>>> list1 = ll * 2
>>> list1
['2', 'hello', 8.9, ['hahhah', 2], '2', 'hello', 8.9, ['hahhah', 2]]
4.連接操作符'+'
>>> list2 = alist + ll
>>> list2
[100, 3, 0, 34, 98, 33, 0.3, 54, 23, '2', 'hello', 8.9, ['hahhah', 2]]
4.列表類型內建函數(shù)
list.append(obj)
list.extend(seq)
list.remove(obj)
list.pop([index=-1])
list.count(obj)返回一個obj在List中出現(xiàn)的次數(shù)
>>> test_list
[100, 3, 0, 34, 98, 33, 0.3, 54, 23, 3, 1234567890, 8.9, 'string', 's']
>>> test_list.count(3)
2
list.index(obj, i=0, j=len(list)) 在i<=k<j之間返回list[k]==obj的k值
>>> test_list.index(1234567890)
10
>>> test_list.index(3, 2, len(test_list)) #查找第二個3
9
list.sort()與list.reverse()無返回值
>>> test_list.sort()
>>> test_list
[0, 0.3, 3, 3, 8.9, 23, 33, 34, 54, 98, 100, 1234567890, 's', 'string']
>>> test_list.reverse()
>>> test_list
['string', 's', 1234567890, 100, 98, 54, 34, 33, 23, 8.9, 3, 3, 0.3, 0]
list.insert(index, value)插入元素
>>> test_list.insert(2, 'import this')
>>> test_list
['string', 's', 'import this', 1234567890, 100, 98, 54, 34, 33, 23, 8.9, 3, 3, 0.3, 0]
5.列表解析
列表解析的一般語法:[元素或者元素的操作
迭代(for)
條件(if)
]
>>> new_list = [x ** 2 for x in range(0, 10) if x % 2 == 0]
>>> new_list
[0, 4, 16, 36, 64]
6.tuple
tuple可以看做不能改變的list掘猿,一旦被定義病游,不可改變
tuple的創(chuàng)建和訪問與list一樣,但是tuple不可更新稠通,更新意味著創(chuàng)建新的tuple
tuple不能刪除一個元素衬衬,只能del atuple
全部刪除
所有多對象的、逗號分隔的改橘、沒有明確用符號定義的滋尉,這些集合的默認類型都是tuple
所有返回的多對象的都是元組類型
7.用列表構建其他數(shù)據(jù)類型
- stack:先入后出
#!/usr/bin/env python
#-*- coding:utf-8 -*-
stack = [] #建立存儲的stack
#進棧
def pushit():
stack.append(raw_input("Please Enter your String : ").strip())
#出棧
def popit():
if len(stack) == 0:
print "Connot pop from an Empty Stack!"
else:
print "Romove [", `stack.pop()`,"] successful!"
#觀察棧
def viewstack():
print stack
CMDs = {'u': pushit, 'o': popit, 'v': viewstack}
#菜單
def showmenu():
pr = """
p(U)sh
P(O)p
(V)iew
(Q)uit
Enter choice: """
while True: #執(zhí)行命令
while True: #接受輸入
try:
choice = raw_input(pr).strip()[0].lower()
except (EOFError, KeyboardInterrupt, IndexError):
choice = 'q'
print '\nYou picked: [%s]' % (choice)
if choice not in 'uovq':
print 'Invalid option, try again'
else:
break
if choice == 'q':
break
CMDs[choice]()
if __name__ == '__main__':
showmenu()
- 隊列:先進先出
#!/usr/bin/env python
#-*- coding:utf-8 -*-
queue = []
# 進隊列
def enQ():
queue.append(raw_input("Please Enter your String : ").strip())
# 出隊列
def delQ():
if len(queue) == 0:
print "Connot pop from an Empty Queue!"
else:
print "Romove [", `queue.pop(0)`, "] successful!" #pop()函數(shù)默認為index = -1
# 觀察隊列
def viewqueue():
print queue
CMDs = {'e': enQ, 'd': delQ, 'v': viewqueue}
# 菜單
def showmenu():
pr = """
(E)nterqueue
(D)delqueue
(V)iew
(Q)uit
Enter choice: """
while True: # 執(zhí)行命令
while True: # 接收輸入
try:
choice = raw_input(pr).strip()[0].lower() # 確保接收輸入的第一個非空格字符的小寫字母
except (EOFError, KeyboardInterrupt, IndexError):
choice = 'q'
print '\nYou picked: [%s]' % (choice)
if choice not in 'devq':
print 'Invalid option, try again'
else:
break
if choice == 'q':
break
CMDs[choice]()
if __name__ == '__main__':
showmenu()