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 关于可变对象和不可变对象的方法的返回值问题
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 元组
①元组用圆括号而列表用方括号
②元组是不可变