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


    习题

    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)
  • 相关阅读:
    Django----博客文章数据返回
    Django----admin模块初识
    Django搭建博客文章---模型层
    Js 提交 form 表单
    sql 查询 between and 和 >= <= 比较
    C# 未能加载项目文件
    不一样的 Null
    Js实现table单双行交替色
    C# 判断一个string型的时间格式是否正确
    利用 Label 小小的提升一下用户体验
  • 原文地址:https://www.cnblogs.com/yuzhenzero/p/7126767.html
Copyright © 2020-2023  润新知