首页 > 编程语言 > 详细

Python作业本——第5章 字典和结构化数据

时间:2017-07-06 22:23:42      阅读:676      评论:0      收藏:0      [点我收藏+]

习题

1.

{}

2.

{fow: 42}

 

3.字典是无序的

4.报错    (KeyError)

5.第一种是既搜索键又搜索值,第二种值搜索键    没有区别,in操作符检查一个值是不是字典的一个键。

6.第一种是既搜索键又搜索值,第二种值搜索值    第一种检查键

7.

spam.setdefault(color, black)

8.pprint模块的pprint函数

 实践项目

5.6.1 好玩游戏的物品清单

 1 stuff = {rope: 1, torch: 6, gold coin:42, dagger: 1, arrow: 12}
 2 
 3 def displayInventory(inventory):
 4     print("inventory:")
 5     item_total = 0
 6     for k, v in inventory.items():
 7         print(str(v) +   + k)
 8         item_total += v
 9     print("Total number of items: " + str(item_total))
10 
11 displayInventory(stuff)

5.6.2 列表到字典的函数,针对好玩游戏物品清单

 1 def displayInventory(inventory):
 2     print("inventory:")
 3     item_total = 0
 4     for k, v in inventory.items():
 5         print(str(v) +   + k)
 6         item_total += v
 7     print("Total number of items: " + str(item_total))
 8 
 9 def addToInventory(inventory, addedItems):
10     for i in addedItems:
11         if i in inventory:
12             inventory[str(i)] = inventory[str(i)] + 1  # 若之前就存在该物品,就将该物品的数量加1
13         else:
14             inventory[str(i)] = 1  # 若之前不存在该物品,就在字典里加上1个该物品
15 
16 inv = {gold coin: 42, rope: 1}
17 dragonLoot = [gold coin, dragger, gold coin, gold coin, ruby]
18 
19 addToInventory(inv, dragonLoot)
20 displayInventory(inv)

 

Python作业本——第5章 字典和结构化数据

原文:http://www.cnblogs.com/yuzhenzero/p/7126767.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!