3.11.2 in操做符和index()
python
先看一段代碼
app
>>> 'record' in music_media False >>> 'H' in music_media True >>> music_media.index('Hello') 1 >>> music_media.index('e') 2 >>> music_media.index('world') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: 'world' is not in list
這裏咱們發現,index()調用時若給定的對象不在列表中Python會報錯,因此檢查一個元素是否在列表中應該用in操做符而不是index(),index()僅適用於已經肯定某元素確實在列表中獲取其索引的狀況。ui
針對上述代碼,能夠作出以下修改code
for eachthing in ('record', 'H', 'Hello', 'e', 'world'): if eachthing in music_media: print music_media.index(eachthing) else: print '%s is not in %s!!' % (eachthing, music_media)
3.11.3 關於可變對象和不可變對象的方法的返回值問題
對象
3.12 列表的特殊特性
索引
3.12.1 用列表構建堆棧
隊列
# -*- coding:utf-8 -*- stack = [] def pushit(): stack.append(raw_input('Enter New string: ').strip()) def popit(): if len(stack) == 0: print "Cannot pop from an empty stack!" else: print 'Removed [', `stack.pop()`, ']' def viewstack(): print stack # calls str() internally CMDs = {'u': pushit, 'o': popit, 'v': viewstack} def showmenu(): pr = ''' p(U)sh p(o)p (V)iew (Q)uit Enter choice: ''' while True: 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()
3.12.2 用列表構建隊列ip
# -*- coding:utf-8 -*- queue = [] def enQ(): queue.append(raw_input('Enter New string: ').strip()) def deQ(): if len(queue) == 0: print 'Cannot pop from an empty queue!' else: print 'Removed [', `queue.pop(0)`, ']' def viewQ(): print queue # calls str internally CMDs = {'e': enQ, 'd': deQ, 'v': viewQ} def showmenu(): pr = ''' (E)nqueue (D)equeue (V)iew (Q)uit Enter choice: ''' while True: 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 'edvq': print 'Invalid option, try again' else: break if choice == 'q': break CMDs[choice]() if __name__ == '__main__': showmenu()
3.13 元組utf-8
①元組用圓括號而列表用方括號input
②元組是不可變