python学习笔记 第五章

字典有点类似链表,但是感觉又不像。不过与json格式差不多。

常用的方法:

spam = {'color': 'red', 'age': 42}
#获取字典的值
print("value:",end="\t")
for v in spam.values():
    print(v)
    
#获取字典的键
print("keys:",end="\t")
for k in spam.keys():
    print(k)
    
#获取字典的键值对
print("items:",end="\t")
for i in spam.items():
    print(i)
value: red
42
keys: color
age
items: ('color', 'red')
('age', 42)

#get方法
picnicItems = {'apples': 5, 'cups': 2}
print('I am bringing ' + str(picnicItems.get('cups', 0)) + ' cups.')
print('I am bringing ' + str(picnicItems.get('eggs', 0)) + ' eggs.')
print("\n")
I am bringing 2 cups.
I am bringing 0 eggs.

#漂亮的输出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(count)
pprint.pprint(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}
{' ': 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}


井字棋盘  bingo小游戏(加强版链接)

#定义一个字典(表格)
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()
    theBoard[move] = turn
    if turn == 'X':
        turn = 'O'
    else:
        turn = 'X'

printBoard(theBoard)
嵌套的字典和列表 

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



实践项目:

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

写一个名为 displayInventory()的函数,它接受任何可能的物品清单

假设征服一条龙的战利品表示为这样的字符串列表:
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
写一个名为 addToInventory(inventory, addedItems)的函数, 其中 inventory 参数
是一个字典, 表示玩家的物品清单( 像前面项目一样), addedItems 参数是一个列表,
就像 dragonLoot。
addToInventory()函数应该返回一个字典, 表示更新过的物品清单。请注意, 列
表可以包含多个同样的项。


# inventory.py
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
#打印方法
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))

#添加方法
def addToInventory(inventory, addedItems):
    # your code goes here
    for i in addedItems:
        for j , k  in  inventory.items():
            if i == j:
                k = k + 1
        if i not in inventory.keys():
            inventory.setdefault(i,1)
    return inventory

inv = {'gold coin': 42, 'rope': 1}
dragonLoot = {'gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'}
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)
Inventory:
42 gold coin
1 dagger
1 rope
1 ruby
Total number of items: 45


 
  

你可能感兴趣的:(python学习笔记 第五章)