今天学习的是:Python Lists and Dictionaries Python 的列表和字典
开篇给定四个动物植:
zoo_animals = ["pangolin", "cassowary", "sloth", "Tiger"];
len(zoo_animals) = 4
前一小节是改变给定的四个动物。只要直接使用
zoo_animals[2] = "hyena"
# Changes "sloth" to "hyena"作用一样
下面做的是增添一个项目:使用到的是一个append()如下:
suitcase = []
# Your code here!
suitcase.append("sunglasses")
suitcase.append("sugar")
suitcase.append("sunshine")
list_length = len(suitcase)
#list_length = # Set this to the length of suitcase
print "There are %d items in the suitcase." % list_length
print suitcase
suitcase = ["sunglasses", "hat", "passport", "laptop", "suit", "shoes"]
first = suitcase[0:2]
middle = suitcase[2:4]
last = suitcase[4:6]
在列举时也可以不用上标或下标如:list[:b]或list[a:]表示从0开始到b前一个结束,和从a开始到最后
接下来做的是查找一个item的位置使用index()来查找位置。
在某个位置插入一个item是用insert()如下:
animals = ["aardvark", "badger", "duck", "emu", "fennec fox"]
duck_index = animals.index("duck")# Use index() to find "duck"
animals.insert(duck_index,'cobra')
print animals # Observe what prints after the insert operation
print duck_index
使用一个list的全部items可以使用For来表示:
for variable in list_name:
# Do stuff!
排序:sort()
start_list = [5, 3, 1, 2, 4]
square_list = []
# Your code here!
for number in start_list:
square_list.append(number**2)
square_list.sort()
print square_list
d = {'key1' : 1, 'key2' : 2, 'key3' : 3}
在要选出1,时要用到print d['key1']
往dictionary里加入item时用下面的语句:
dict_name[new_key] = new_value
删除语句如下,只能一个一个的删除。
del dict_name[key_name]
del()与.remove()的区别如下 :
del
deletes a key and its value based on the key you tell it to delete..remove()
removes a key and its value based on the value you tell it to delete.
dict_name['list_key'].list_function()