Python 入门教程 8 ---- Python Lists and Dictionaries


 第一节

     1 介绍了Python的列表list

     2 列表的格式list_name = [item1 , item2],Python的列表和C语言的数组很像

     3 列表可以为空,就是empty_list = [],比如数组为空

     4 举例

zoo_animals = ["pangolin", "cassowary", "sloth", "dog"];
# One animal is missing!

if len(zoo_animals) > 3:
	print "The first animal at the zoo is the " + zoo_animals[0]
	print "The second animal at the zoo is the " + zoo_animals[1]
	print "The third animal at the zoo is the " + zoo_animals[2]
	print "The fourth animal at the zoo is the " + zoo_animals[3]

 第二节

     1  介绍了我们可以使用下标来访问list的元素,就像数组一样

     2 下标从0开始,比如list_name[0]是第一个元素

     3 练习:输出列表numbers的第二个和第四个数的和

numbers = [5, 6, 7, 8]

print "Adding the numbers at indices 0 and 2..."
print numbers[0] + numbers[2]
print "Adding the numbers at indices 1 and 3..."
# Your code here!
print numbers[1] + numbers[3]


 第三节

     1 介绍了我们可以使用下标来对第几个元素进行赋值

     2 比如lisy_name[2] = 2,就是把列表的第三个值赋值为2

     3 练习:把列表zoo_animals中的tiger换成其它的动物

zoo_animals = ["pangolin", "cassowary", "sloth", "tiger"]
# Last night our zoo's sloth brutally attacked 
#the poor tiger and ate it whole.

# The ferocious sloth has been replaced by a friendly hyena.
zoo_animals[2] = "hyena"

# What shall fill the void left by our dear departed tiger?
# Your code here!
zoo_animals[3] = "dog"


 第四节

     1 介绍了list中添加一个item的方法append()

     2 比list_name.append(item),求列表list_name中有几项就是利用len(list_name)

     3 练习:在列表suitcase在增加三项,然后求出它的元素的个数

suitcase = [] 
suitcase.append("sunglasses")

# Your code here!
suitcase.append("a")
suitcase.append("b")
suitcase.append("c")

# Set this to the length of suitcase
list_length = len(suitcase)

print "There are %d items in the suitcase." % (list_length)
print suitcase


 第五节

     1 介绍了list列表怎样得到子列表list_name[a:b],将得到下标a开始到下标b之前的位置

     2 比如列表my_list = [1,2,3,4],那么my_list[1:3]得到的将是[2,3]

my_list = [0, 1, 2, 3]
my_slice = my_list[1:3]
print my_list
# Prints [0, 1, 2, 3]
print my_slice
# Prints [1, 2]

     3 如果我们默认第二个值,那么将会直接到末尾那个位置。如果默认第一个值,值是从头开始

my_list[:2]
# Grabs the first two items
my_list[3:]
# Grabs the fourth through last

     4 练习:把first列表设置为suitcase的前两项,把middle列表设置为suitcase的中间两项,把last列表设置为suitcase的后两项

suitcase = ["sunglasses", "hat", "passport", "laptop", "suit", "shoes"]

# The first two items
first = suitcase[0:2] 
# Third and fourth items
middle = suitcase[2:4]
# The last two items
last = suitcase[4:]


  第六节

     1 介绍了不仅列表可以得到子串,字符串也满足

     2 比如string[a:b]是得到从下标a开始到b之前的子串

     3 练习:把三个变量分别设置为对应的子串

animals = "catdogfrog"
# The first three characters of animals
cat = animals[:3]   
# The fourth through sixth characters
dog = animals[3:6]   
# From the seventh character to the end
frog = animals[6:] 


 第七节

     1 介绍了列表的两种方法index(item)和insert(index , item)

     2 index(item)方法是查找item在列表中的下标,使用方法list_name.index(item)

     3 insert(index,item)是在下标index处插入一个item,其余的后移,使用方法list_name.insert(index , item)

     4 练习:使用index()函数找到列表中的"duck",然后在当前位置插入"cobra"

                   如果我们使用print list_name,就是直接输出列表的所有元素

animals = ["aardvark", "badger", "duck", "emu", "fennec fox"]
# Use index() to find "duck"
duck_index = animals.index("duck")

# Your code here!
animals.insert(duck_index,"cobra")

# Observe what prints after the insert operation
print animals 

 第九节

     1 介绍我们可以使用for循环来遍历列表的每一个元素

     2 比如for variable in list_name:

                     statement

        这样我们可以枚举列表的每一个元素

     3 练习:打印列表的每一个元素的值*2

my_list = [1,9,3,8,5,7]

for number in my_list:
    # Your code here
    print 2*number


  第十节

     1 介绍了列表的另外一种方法sort(),可以对列表进行排序,默认是从小到打排序

     2 使用的方法是list_name.sort()

     3 列表中删除一个item的方法list_name.remove(item)  

beatles = ["john","paul","george","ringo","stuart"]
beatles.remove("stuart")
print beatles
>> ["john","paul","george","ringo"]

     4 练习:利用for循环把没一项的值的平方加入列表square_list,然后对square_list排序输出

start_list = [5, 3, 1, 2, 4]
square_list = []

# Your code here!
for numbers in start_list:
    square_list.append(numbers**2)
print square_list.sort()


 第十一节

     1 介绍了Python中的字典,字典的每一个item是一个键值对即key:value

     2 比如字典d = {'key1' : 1, 'key2' : 2, 'key3' : 3},有三个元素

     3 Python的字典和C++里面的map很像,我们可以使用d["key1"]来输出key1对应的value

     4 练习:打印出'Sloth'和'Burmese Python'对应的value

                   注意在脚本语言里面可以使用单引号也可以使用双引号来表示字符串

# Assigning a dictionary with three key-value pairs to residents:
residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106}

# Prints Puffin's room number
print residents['Puffin'] 

# Your code here!
print residents['Sloth']
print residents['Burmese Python']


 第十二节

     1 介绍了三点

        1 字典和列表一样可以是空的,比如d = {}就是一个空的字典

        2 字典里面添加一个键值对或者是改变已有key的value,使用这种方法 dict_name[key] = value
        3 我们也可以使用len(dict_name)求出字典的元素的个数

     2 练习:至少添加3个键值对到字典menu中

# Empty dictionary
menu = {} 

# Adding new key-value pair
menu['Chicken Alfredo'] = 14.50 
print menu['Chicken Alfredo']

# Your code here: Add some dish-price pairs to menu!
menu["a"] = 1
menu["b"] = 2
menu["c"] = 3

# print you code
print "There are " + str(len(menu)) + " items on the menu."
print menu


 第十三节

     1 介绍了我们可以删除字典中的键值对

     2 我们使用del dict_name[key],这样将删除键值为key的键值对

     3 练习:删除key为"Sloth"和"Bengal Tiger",并且设置key为"Rockhopper Penguin"的val和之前的不一样

# key - animal_name : value - location 
zoo_animals = { 'Unicorn' : 'Cotton Candy House',
'Sloth' : 'Rainforest Exhibit',
'Bengal Tiger' : 'Jungle House',
'Atlantic Puffin' : 'Arctic Exhibit',
'Rockhopper Penguin' : 'Arctic Exhibit'}

# A dictionary (or list) declaration may break across multiple lines
# Removing the 'Unicorn' entry. (Unicorns are incredibly expensive.)
del zoo_animals['Unicorn']

# Your code here!
del zoo_animals["Sloth"]
del zoo_animals["Bengal Tiger"]
zoo_animals["Rockhopper Penguin"] = "aa"

# print you code
print zoo_animals


 第十四节

     1 介绍了字典中一个key可以对应不止一个的value

     2 比如my_dict = {"hello":["h","e","l","l","o"]},那么key为"hello"对应的value有5个,我们可以使用my_dict["hello"][index]来取得下标为index的value,比如index为1的时候是"e"

     3 对于一个key对应多个value的话,我们应该要用list来保存这些value

     4 对于一个key对应多个value的话,我们还可以对这个key的val进行排序,比如my_dict["hello"].sort()

     4 练习

        1 在字典inventory中添加一个key为'pocket',值设置为列表["seashell" , "strange berry" , "lint"]

        2 对key'pocket'的value进行排序

        3 删除字典inventory中key为'backpack'的键值对

        4 把字典inventory中key为'gold'的value加一个50

# Assigned a new list to 'pouch' key
inventory = {'gold' : 500,
'pouch' : ['flint', 'twine', 'gemstone'], 
'backpack' : ['xylophone','dagger', 'bedroll','bread loaf']}

# Adding a key 'burlap bag' and assigning a list to it
inventory['burlap bag'] = ['apple', 'small ruby', 'three-toed sloth']

# Sorting the list found under the key 'pouch'
inventory['pouch'].sort() 
# Here the dictionary access expression takes the place of a list name 

# Your code here
inventory['pocket'] = ["seashell" , "strange berry" , "lint"]
inventory['pocket'].sort()
del inventory['backpack']
inventory['gold'] = [500 , 50]




你可能感兴趣的:(Python 入门教程 8 ---- Python Lists and Dictionaries)