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 them
10 cities = {
11     'CA': 'San Francisco',
12     'MI': 'Detroit',
13     'FL': 'Jacksonville'
14 }
15 
16 # add some more cities
17 cities['NY'] = 'New York'
18 cities['OR'] = 'Portland'
19 
20 # print out some cities
21 print '-' * 10
22 print "NY State has: ", cities['NY']
23 print "OR State has: ", cities['OR']
24 
25 # print some states
26 print '-'*10
27 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 dict
31 print '-'*10
32 print "Michigan has: ", cities[states['Michigan']]
33 print "Florida has: ", cities[states['Florida']]
34 
35 # print every state abbreviation
36 print '-'*10
37 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 '-'*10
42 for abbrev, city in cities.items():
43     print "%s has the city %s" % (abbrev, city)
44 
45 # now do both at the same time
46 print '-'*10
47 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 '-'*10
52 # safely get a abbreviation by state that might not be there
53 state = states.get('Texas', None)
54 
55 if not state:
56     print "Sorry, no Texas."
57 
58 # get a city with a default value
59 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()相当于遍历这个列表,所以后面不再加参数。

转载于:https://www.cnblogs.com/EiffelRachel/p/5891894.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值