python核心编程-第六章-我的笔记(二)

    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

②元组是不可变

相关文章
相关标签/搜索