python学习(二)

python字典操作

  Python字典(Dictionary)是一种映射结构的数据类型,由无序的“键-值对”组成。字典的键必须是不可改变的类型,如:字符串,数字,tuple;值可以为任何Python数据类型。

1.新建字典

>>> dicta = {}
>>> type(dicta)
<type 'dict'>

2.给字典增加value

>>> dicta['name'] = 'nh'
>>> print dicta
{'name': 'nh'}

3.给字典增加元素

>>> dicta = {}
>>> type(dicta)
<type 'dict'>
>>> dicta['name'] = 'nh'
>>> print dicta
{'name': 'nh'}
>>> dicta['sex'] = 'boy'
>>> print dicta
{'name': 'nh', 'sex': 'boy'}

注意:给字典增加新元素key:value,直接以赋值的方式增加就行,无需事先定义。

4.删除字典

#删除指定键-值对 
>>> del dicta['sex']    #也可以用pop方法,dict1.pop('sex')
>>> print dicta
{'name': 'nh'}

#清空字典
>>> dicta.clear()
>>> print dicta
{}

#删除字典对象
>>> del dicta
>>> print dicta
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'dicta' is not defined

5.字典的遍历

>>> print dicta
{'name': 'nh', 'sex': 'boy'}
>>> for i in dicta:    #遍历字典key
...     print i
... 
name
sex
>>> for i in dicta:    #遍历字典value
...     print i, dicta[i]
... 
name nh
sex boy

 6.一个练习题——公交换乘

  1. 项目要求:用户输入起点,再输入终点站。 我们程序根据 公交站的字典查找到换乘的位置。
  2. 我们程序要:提示 换乘站 和换乘路线。
  3. 我们先从简单的入手,只考虑俩辆公交换乘。数据如下:
    375:西直门,文慧桥,蓟门桥,学院路,知春路
    562:蓟门桥,学院路,中关村
    387:学院路,北京西站

    思路:读取数据,将每一路车表示成一个字典,字典的key为公交号码bus_name及站点station,用split方法取出key的值。由于每路车有多个站点,所以将这些站点保存在列表中。然后判断出发站点和终止站点分别在哪路车中(即哪个列表中),运用set(l1)&set(l2)比较这两个列表的交集,即是换乘站。具体实现如下:

     1 #coding:utf-8
     2 
     3 f = open('bus.txt')    #保存数据的文件
     4 all_bus = f.readlines()
     5 f.close()
     6 
     7 start = "西直门"
     8 end = "北京西站"
     9 dict_bus = {}
    10 list_bus = []
    11 
    12 for i in all_bus:
    13         i = i.strip('
    ')    #去掉结尾的换行符
    14         dict_bus = {}
    15         dict_bus['station'] = i.split(':')[1].split(',')    #给station赋值
    16         dict_bus['busname'] = i.split(':')[0]    #给busname赋值
    17         list_bus.append(dict_bus)    #保存入列表
    18 #print list_bus
    19 
    20 for i in list_bus:
    21         one_station = i.values()[1]
    22         if start in one_station:
    23                 start_bus = i.values()[0]
    24                 l1 = one_station
    25         if end in one_station:
    26                 end_bus = i.values()[0]
    27                 l2 = one_station
    28 
    29 l3 = set(l1) & set(l2)    #取交集
    30 #print list(l3)
    31 print "%s=>" %start_bus,
    32 for bus in list(l3):
    33         print bus,
    34 print "=>%s" %end_bus

    运行结果:

    root@***:~# python test11.py
    375=> 学院路 =>387

     

原文地址:https://www.cnblogs.com/goodhacker/p/3149522.html