第38个python程序:列表的操作

[root@mysql1 pshell]# cat ex38.py 
#!/usr/bin/env Python
#-*-coding:utf-8-*-


# create a mapping of state to abbreviation


states={
  'oregon': 'or',
  'florida': 'fl',
  'california': 'ca',
  'new york': 'ny',
  'michigan': 'mi'
}


# create a basic set of states and some cities in them


cities={
  'ca': 'san francisco',
  'mi': 'detroit',
  'fl': 'jacksonville'
}


# add some more cities


cities['ny']='new york'
cities['or']='portland'


# print out some cities


print '-' * 10
print "ny state has: ", cities['ny']
print "or state has: ", cities['or']


# print some states
print '-' * 10
print "michigan's abbreviation is: ", states['michigan']
print "florida's abbreviation is: ", states['florida']


# do it by using the state then cities dict
print '-' * 10
print "michigan has: ", cities[states['michigan']]
print "florida has: ", cities[states['florida']]


# print every state abbreviation
print '-' * 10
for state, abbrev in states.items():
  print "%s is abbreviated %s" % (state, abbrev)


# print every city in state
print '-' * 10
for abbrev,city in cities.items():
  print "%s has the city %s" % (abbrev, city)


# now do both at the same time
print '-' * 10
for state,abbrev in states.items():
  print "%s state is abbreviated %s and has city %s" % (state, abbrev, cities[abbrev])


print '-' * 10


# safely get a abbreviation by state that might not be there
state=states.get('texas', None)


if not state:
  print "sorry, no texas."


# get a city with a default value
city=cities.get('tx', 'does not exist')
print "the city for the state 'tx' is: %s" % city
[root@mysql1 pshell]# 
[root@mysql1 pshell]# 
[root@mysql1 pshell]# 
[root@mysql1 pshell]# 
[root@mysql1 pshell]# python ex38.py 
----------
ny state has:  new york
or state has:  portland
----------
michigan's abbreviation is:  mi
florida's abbreviation is:  fl
----------
michigan has:  detroit
florida has:  jacksonville
----------
california is abbreviated ca
michigan is abbreviated mi
new york is abbreviated ny
florida is abbreviated fl
oregon is abbreviated or
----------
fl has the city jacksonville
ca has the city san francisco
mi has the city detroit
or has the city portland
ny has the city new york
----------
california state is abbreviated ca and has city san francisco
michigan state is abbreviated mi and has city detroit
new york state is abbreviated ny and has city new york
florida state is abbreviated fl and has city jacksonville
oregon state is abbreviated or and has city portland
----------
sorry, no texas.
the city for the state 'tx' is: does not exist
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值