Chinaunix首页 | 论坛 | 博客
  • 博客访问: 945235
  • 博文数量: 194
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 2094
  • 用 户 组: 普通用户
  • 注册时间: 2018-11-02 11:19
文章分类

全部博文(194)

文章存档

2019年(162)

2018年(32)

我的朋友

分类: Python/Ruby

2019-07-02 10:03:27

5.1 字典数据类型

字典的索引可以使用许多不同类型的数据,不只是整数。字典的索引被称为“键”,键及其关联的值称为“键—值”对,在代码中,字典输入时带花括号{}。

字典中的表项是不排序的,所以字典不能像列表那样切片。

5.1.1 keys()、values()和items()方法

key()、values()和items()方法将返回类似于列表的值,分别对应于字典的键、值和键-值对。这些方法返回的值不是真正的列表,他们不能被修改,没有append()方法。但这些数据类型可以用于for循环。

>>> spam = {'color':'red','age':42} >>> for i in spam.values(): print (i)

red 42 

可以通过list()方法将字典转换为列表

>>> list(spam.keys())
['color', 'age'] >>> list(spam.values())
['red', 42] >>> spam
{'color': 'red', 'age': 42} 

5.1.2 get()方法setdefault()方法

get()方法有两个参数:要取得其值的键,以及如果该键不存在时,返回的备用值

setdefault()方法提供了一种方式,传递给该方法的第一个参数,是要检查的键,第二个参数,是如果该键不存在时要设置的值。如果该键存在就返回键值。

如果程序中导入了pprint()模块,就可以使用pprint()和pformat()打印字典。

import pprint
message = 'It was a bright cold day in April, and the clocks were striking thirteen.' count = {} for character in message: count.setdefault(character, 0) count[character] = count[character] + 1 print(pprint.pformat(count)) #pprint.pprint(count)  print(pprint.pformat(count))这两种表达式等价 

运行结果:

{' ': 13, ',': 1, '.': 1, 'A': 1, 'I': 1, 'a': 4, 'b': 1, 'c': 3, 'd': 3, 'e': 5, 'g': 2, 'h': 3, 'i': 6, 'k': 2, 'l': 3, 'n': 4, 'o': 2, 'p': 1, 'r': 5, 's': 3, 't': 6, 'w': 2, 'y': 1} 
5.2 实践项目
  1. 好玩游戏的物品清单

你在创建一个好玩的视频游戏。用于对玩家物品清单建模的数据结构是一个字典。其中键是字符串,描述清单中的物品,值是一个整型值,说明玩家有多少该物品。例如,字典值{'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1,'arrow': 12}意味着玩家有 1 条绳索、6 个火把、42 枚金币等。 写一个名为displayInventory()的函数,它接受任何可能的物品清单,并显示如下:

Inventory: 1 rop 6 torch 42 gold coin 1 dagger 12 arrow Total number of items :  62 

代码如下:

def displayInventory(dic): print('Inventory:') count = 0 for k, v in dic.items(): print(str(v) + ' ' + k) count = v+count print('Total number of items : ', count)


dicValue = {'rop': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
displayInventory(dicValue) 
  1. 假设征服一条龙的战利品表示为这样的字符串列表:
dragonLoot = ['gold coin', 'digger', 'gold coin', 'gold coin', 'ruby'] 

写一个名为 addToInventory(inventory, addedItems)的函数,其中 inventory 参数 是一个字典,表示玩家的物品清单(像前面项目一样),addedItems 参数是一个列表, 就像 dragonLoot。 addToInventory()函数应该返回一个字典,表示更新过的物品清单。

def displayInventory(dic): print('Inventory:')
    count = 0 for k, v in dic.items():
        print(str(v) + ' ' + k)
        count = v+count
    print('Total number of items : ', count) def addToInventory(inventory, addeditems): for i in addeditems: if i in inventory.keys():
            inventory[i] += 1 else:
            inventory.setdefault(i, 1) return inventory


inv = {'gold coin':42, 'rope':1}
dragonLoot = ['gold coin', 'digger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv,dragonLoot)
displayInventory(inv) 

前面的程序(加上前一个项目中的 displayInventory()函数)将输出如下:

Inventory: 45 gold coin 1 rope 1 digger 1 ruby Total number of items :  48
阅读(292500) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~