温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python字典和结构化数据

发布时间:2020-08-06 19:47:17 来源:ITPUB博客 阅读:201 作者:安全剑客 栏目:编程语言
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)
red42

可以通过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] + 1print(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 rop6 torch52 gold coin1 dagger12 arrowTotal 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 coin1 rope1 digger1 rubyTotal number of items :  48


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI