第 12 章
测试题
可以使用 append()、insert() 或 extend() 向列表增加元素。
可以使用 remove()、pop() 或 del() 从列表删除元素。
要得到列表的一个有序副本,可以采用下面任意一种做法:
建立列表的副本,使用分片:new_list = my_list[:],然后对新列表排序:new_list.sort()
使用 sorted() 函数:new_list = sorted(my_list)
使用 in 关键字可以得出一个特定值是否在一个列表中。
使用 index() 方法可以得出一个值在列表中的位置。
元组是一个与列表类似的集合,只不过元组不能改变。元组是不可改变的, 而列表是可改变的。
可以采用多种方法建立一个双重列表。
- 使用嵌套的中括号:
>>> my_list =[[1, 2, 3],['a','b','c'],['red', 'green', blue']]
- 使用 append(),并追加一个列表:
>>> my_list = []
>>> my_list.append([1, 2, 3])
>>> my_list.append(['a', 'b', 'c'])
>>> my_list.append(['red', 'green', 'blue'])
>>> print my_list
[[1, 2, 3], ['a', 'b', 'c'], ['red', 'green', 'blue']]
- 建立单个列表,再合并这些列表:
>>> list1 = [1, 2, 3]
>>> list2 = ['a', 'b', 'c']
>>> list3 = ['red', 'green', 'blue']
>>> my_list = [list1, list2, list3]
>>> print my_list
[[1, 2, 3], ['a', 'b', 'c'], ['red', 'green', 'blue']]
- 可以使用两个索引得到双重列表中的一个值:
my_list = [[1, 2, 3], ['a', 'b', 'c'], ['red', 'green', 'blue']]
my_color = my_list[2][1]
这个答案是 'green'。
字典是键值对的集合。
你可以通过指定键和值的方式在字典中添加条目:
phone_numbers['John'] = '555-1234'
- 要通过键在字典中查找一个条目,可以使用索引:
print phone_numbers['John']
动手试一试
- 下面这个程序会得到 5 个名字,把它们放在一个列表中,然后打印出来:
nameList = []
print "Enter 5 names (press the Enter key after each name):"
for i in range(5):
name = raw_input()
nameList.append(name)
print "The names are:", nameList
- 下面这个程序会打印原来的列表和排序后的列表:
nameList = []
print "Enter 5 names (press the Enter key after each name):"
for i in range(5):
name = raw_input()
nameList.append(name)
print "The names are:", nameList
print "The sorted names are:", sorted(nameList)
- 下面这个程序只打印列表中的第 3 个名字:
nameList = []
print "Enter 5 names (press the Enter key after each name):"
for i in range(5):
name = raw_input()
nameList.append(name)
print "The third name is:", nameList[2]
- 下面这个程序允许用户替换列表中的一个名字:
nameList = []
print "Enter 5 names (press the Enter key after each name):"
for i in range(5):
name = raw_input()
nameList.append(name)
print "The names are:", nameList
print "Replace one name. Which one? (1-5):",
replace = int(raw_input())
new = raw_input("New name: ")
nameList[replace - 1] = new
print "The names are:", nameList
- 下面这个程序允许用户创建包含单词和对应定义的词典:
user_dictionary = {}
while 1:
command = raw_input("'a' to add word,'l' to lookup a word,'q' to quit")
if command == "a":
word = raw_input("Type the word: ")
definition = raw_input("Type the definition: ")
user_dictionary[word] = definition
print "Word added!"
elif command == "l":
word = raw_input("Type the word: ")
if word in user_dictionary.keys():
print user_dictionary[word]
else:
print "That word isn't in the dictionary yet."
elif command == 'q':
break
