首页 > 代码库 > python学习04——列表的操作

python学习04——列表的操作

笨办法学python第38节

如何创建列表在第32节,形式如下:

技术分享

本节主要是讲对列表的操作,首先讲了 mystuff.append(‘hello‘) 的工作原理,我的理解是,首先Python找到mystuff这个变量,然后进行append()这个函数操作。其中需要注意的是括号()里面有一个额外参数就是mystuff本身。

 

本文练习:

 1 # create a mapping of state to abbreviation 2 states = { 3     Oregon: OR, 4     Florida: FL, 5     California: CA, 6     Michigan: MI 7 } 8  9 # create a basic set of states and some cities in them10 cities = {11     CA: San Francisco,12     MI: Detroit,13     FL: Jacksonville14 }15 16 # add some more cities17 cities[NY] = New York18 cities[OR] = Portland19 20 # print out some cities21 print - * 1022 print "NY State has: ", cities[NY]23 print "OR State has: ", cities[OR]24 25 # print some states26 print -*1027 print "Michigan‘s abbreviation is: ", states[Michigan]28 print "Florida‘s abbreviation is: ", states[Florida]29 30 # do it by using the state then cities dict31 print -*1032 print "Michigan has: ", cities[states[Michigan]]33 print "Florida has: ", cities[states[Florida]]34 35 # print every state abbreviation36 print -*1037 for state, abbrev in states.items():38     print "%s is abbreviated %s" % (state, abbrev)39 40 # print every city in state   (why not sequence)41 print -*1042 for abbrev, city in cities.items():43     print "%s has the city %s" % (abbrev, city)44 45 # now do both at the same time46 print -*1047 for state, abbrev in states.items():48     print "%s state is abbreviated %s and has city %s" % (49         state, abbrev, cities[abbrev])50 51 print -*1052 # safely get a abbreviation by state that might not be there53 state = states.get(Texas, None)54 55 if not state:56     print "Sorry, no Texas."57 58 # get a city with a default value59 city = cities.get(TX, Does Not Exist)60 print "The city for the state ‘TX‘ is: %s" % city

存在的问题:

1. 40行的输出城市名称,运行时输出的并不是顺序输出的,这个输出遵循的规律是什么?

2. states.items(),按照书里说的()里面有一个额外参数states,所以在这个()里面不加参数,因为里面的参数就是前面的列表,那如果想再加一个参数在()里面,如何加?

回答:

1. Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。

    dict内部存放的顺序和key放入的顺序是没有关系的,dict的查找是根据哈希表查找的,所以输出不是顺序输出的。

2. 这个和书里的那个函数不一样,书里的那个函数是append(),这个item()相当于遍历这个列表,所以后面不再加参数。

python学习04——列表的操作