python核心编程-第六章-个人笔记(二)

本文深入探讨了Python中列表的in操作符、index()函数及其实用案例,包括使用列表构建堆栈与队列,并介绍了元组的基本概念与特性。通过实例代码演示,帮助读者掌握列表及其相关数据结构的应用。

    3.11.2  in操作符和index()

        先看一段代码

>>> '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()仅适用于已经确定某元素确实在列表中获取其索引的情况。

针对上述代码,可以做出如下修改

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   关于可变对象和不可变对象的方法的返回值问题

083341_8M1D_2297516.png

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  用列表构建队列

# -*- 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  元组

①元组用圆括号而列表用方括号

②元组是不可变

转载于:https://my.oschina.net/u/2297516/blog/545848

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值