測試題
1. 可以使用 append
、insert
或 extend
向列表增加元素。
2. 可以使用 remove
、pop
或 del
從列表刪除元素。
3. 要得到列表的一個有序副本,可以採用下面任意一種做法:
建立列表的副本,使用分片:
new_list = my_list[:]
,然後對新列表排序:new_list.sort
使用
sorted
函數:new_list = sorted(my_list)
4. 使用 in
關鍵字可以得出一個特定值是否在一個列表中。
5. 使用 index
方法可以得出一個值在列表中的位置。
6. 元組是一個與列表類似的集合,只不過元組不能改變。元組是不可改變的, 而列表是可改變的。
7. 可以採用多種方法建立一個雙重列表。
使用嵌套的中括號:
>>> 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']]
8. 可以使用兩個索引得到雙重列表中的一個值:
my_list = [[1, 2, 3], ['a', 'b', 'c'], ['red', 'green', 'blue']]my_color = my_list[2][1]
這個答案是 'green'
。
9. 字典是鍵值對的集合。
10. 你可以通過指定鍵和值的方式在字典中添加條目:
phone_numbers['John'] = '555-1234'
11. 要通過鍵在字典中查找一個條目,可以使用索引:
print phone_numbers['John']
動手試一試
1. 下面這個程序會得到 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
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:", nameListprint "The sorted names are:", sorted(nameList)
3. 下面這個程序只打印列表中的第 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]
4. 下面這個程序允許用戶替換列表中的一個名字:
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:", nameListprint "Replace one name. Which one? (1-5):",replace = int(raw_input)new = raw_input("New name: ")nameList[replace - 1] = newprint "The names are:", nameList
5. 下面這個程序允許用戶創建包含單詞和對應定義的詞典:
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] = definitionprint "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