python 字典

一、字典

  1. 字典是可变数据类型,可以存储任意类型的对象。
  2. 字典是无序的。故也不能切片。访问字段的时候访问键值就可以。
  3. 键值对需要注意的几点:
    • 键是唯一的,值可以变;一个键可以对应多值,之间用逗号隔开,如:dict={‘a’:1,2,3};值也可以是一个字典
    • 字典值是任意的python对象,可以是标准的对象,也可以是用户自定义的,但是键不行
    • 不允许同 一个键出现两次,创建时如果同一个键被赋值两次,后一个会被记住
    • 键必须是不可变数据类型,可以是字符串、数字;元祖而列表就不行
    • 同时键也可以使用布尔值(True False),但是若是已经有键是0,1,那就无法使用布尔值了

二、实例

1.用setdefault方法统计字符串中每个字符出现的次数。

#1.用setdefault方法统计字符串中每个字符出现的次数
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 #以字符为key,匹配一次对应value就加1
print(count)

运行后结果为:

{'I': 1, 't': 6, ' ': 13, 'w': 2, 'a': 4, 's': 3, 'b': 1, 'r': 5, 'i': 6, 'g': 2, 'h': 3, 'c': 3, 'o': 2, 'l': 3, 'd': 3, 'y': 1, 'n': 4, 'A': 1, 'p': 1, ',': 1, 'e': 5, 'k': 2, '.': 1}
  1. 井字数据游戏
#井字数据结构
theBoard={'top-L':'','top-M':'','top-R':'',
          'mid-L':'','mid-M':'','mid-R':'',
          'low-L':'','low-M':'','low-R':''}
def printBoard(board):
    print(board['top-L']+'|'+board['top-M']+'|'+board['top-R'])
    print('-+-+-')
    print(board['mid-L']+'|'+board['mid-M']+'|'+board['mid-R'])
    print('-+-+-')
    print(board['low-L']+'|'+board['low-M']+'|'+board['low-R'])

#玩家
turn='X' #先手棋子
for i in range(9):
     printBoard(theBoard)
     print('Turn for'+turn+'.Move on which space?')
     move=input() #指定棋盘key,准备落子
     theBoard[move]=turn
     if turn=='X':
         turn='O' #对方落子
     else:
         turn='X'
printBoard(theBoard)

运行后结果为:

o|o|o
-+-+-
x||
-+-+-
||

3.计算客人带来的食物数量

# 计算客人带来的食物的数量
allGuests={'Alice':{'apples':5,'pretzels':12},
           'Bob':{'ham sandwiches':3,'apples':2},
           'Carol':{'cups':3,'apple pies':1}}

def totalBrought(guests,item):
    numBrought=0
    for k,v in guests.items():
        numBrought=numBrought+v.get(item,0)
    return numBrought

print('Number of things being brought:')
print(' - Apples ' + str(totalBrought(allGuests, 'apples')))
print(' - Cups ' + str(totalBrought(allGuests, 'cups')))
print(' - Cakes ' + str(totalBrought(allGuests, 'cakes')))
print(' - Ham Sandwiches ' + str(totalBrought(allGuests, 'ham sandwiches')))
print(' - Apple Pies ' + str(totalBrought(allGuests, 'apple pies')))

运行结果为:

Number of things being brought:
 - Apples 7
 - Cups 3
 - Cakes 0
 - Ham Sandwiches 3
 - Apple Pies 1

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

#  习题:统计玩家物品的数量
stuff={'rope':1,'torch':6,'gold coin':43,'dragger':1,'arrow':12}

def displayInventory(inventory):
    print('Inventory')
    item_total=0
    for k,v in inventory.items():
        print(str(v)+''+k)
        item_total+=v
    print('Total number of items:'+str(item_total))
displayInventory(stuff)
 运行结果为:
Inventory
1rope
6torch
43gold coin
1dragger
12arrow
Total number of items:63
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值