Published 12月 25, 2018 by with 0 comment

Automate The Boring Stuff With Python - Chapter 5 - 字典和結構化數據




今天是看這本書Automate the Boring Stuff with Python(Python編程快速上手--讓繁瑣工作自動化)
第5章節(Dictionaries and Structuring Data)所做的練習

這章主要講字典(Dictionary)
字典的表示方式是花括號{}
aaa, bbb表示鍵(Key), 111, BbB表示值(Value)
spam = {'aaa': 111, 'bbb': 'BbB'}

取出字典某一鍵對應的值
>>> spam = {'aaa': 111, 'bbb': 'BbB'}
>>> spam['aaa']
111

修改某一鍵對應的值
>>> spam = {'aaa': 111, 'bbb': 'BbB'}
>>> spam['aaa'] ='AAA'
>>> spam['aaa']
'AAA'

新增一鍵-值到字典
>>> spam = {'aaa': 111, 'bbb': 'BbB'}
>>> spam['ccc'] = '333'
>>> spam
{'aaa': 111, 'bbb': 'BbB', 'ccc': '333'}

可用del刪除字典內的鍵-值
>>> spam = {'aaa': 111, 'bbb': 'BbB', 'ccc': '333'}
>>> del spam['ccc']
>>> spam
{'aaa': 111, 'bbb': 'BbB'}

可用for + keys() 來返回字典的每一個鍵
>>> spam = {'aaa': 111, 'bbb': 'BbB'}
>>> for k in spam.keys():
    print(k)

aaa
bbb

可用for + values() 來返回字典的每一個值
>>> spam = {'aaa': 111, 'bbb': 'BbB'}
>>> for v in spam.values():
    print(v)
    
111
BbB

可用for + items() 來返回字典的每一個鍵-值
>>> spam = {'aaa': 111, 'bbb': 'BbB'}
>>> for i in spam.items():
    print(i)

('aaa', 111)
('bbb', 'BbB')

可用get()來取得鍵之值, 若該鍵不存在, 則返回備用值.
>>> spam = {'aaa': 111, 'bbb': 'BbB'}
>>> spam.get('aaa', 0)
111
>>> spam.get('ccc', 0)
0
>>> spam
{'aaa': 111, 'bbb': 'BbB'}

可用setdefault()來給字典加入兩個參數, 第一個是要檢查的鍵.
第二個參數是若該鍵值不存在, 則將第二參數的值返回.
>>> spam = {'aaa': 111, 'bbb': 'BbB'}
>>> spam.setdefault('aaa', 0)
111
>>> spam.setdefault('ccc', 333)
333
>>> spam
{'aaa': 111, 'bbb': 'BbB', 'ccc': 333}
>>> spam.setdefault('ccc', '444')
333 

這可以計算一段訊息內出現幾次相同的字.
並利用pprint 更好看的印出來
>>> import pprint
>>> message = 'Hello, World!. This is Peter, I want to go to AWS and study AWS tech.'
>>> count ={}
>>> for word in message:
    count.setdefault(word, 0)
    count[word] = count[word] + 1
>>> print(count)
{'H': 1, 'e': 4, 'l': 3, 'o': 5, ',': 2, ' ': 14, 'W': 3, 'r': 2, 'd': 3, '!': 1, '.': 2, 'T': 1, 'h': 2, 'i': 2, 's': 3, 'P': 1, 't': 6, 'I': 1, 'w': 1, 'a': 2, 'n': 2, 'g': 1, 'A': 2, 'S': 2, 'u': 1, 'y': 1, 'c': 1}
>>> 
>>> pprint.pprint(count)
{' ': 14,
 '!': 1,
 ',': 2,
 '.': 2,
 'A': 2,
 'H': 1,
 'I': 1,
 'P': 1,
 'S': 2,
 'T': 1,
 'W': 3,
 'a': 2,
 'c': 1,
 'd': 3,
 'e': 4,
 'g': 1,
 'h': 2,
 'i': 2,
 'l': 3,
 'n': 2,
 'o': 5,
 'r': 2,
 's': 3,
 't': 6,
 'u': 1,
 'w': 1,
 'y': 1}
>>> 


章節5習題, 用Notepad++打下列的程式碼,
另存為Chapter_5.py. 我附上中文注釋方便好讀.
# -*- coding: UTF-8 -*-
# http://juilin77.blogspot.com/
# v20181225
# Automate The Boring Stuff With Python - Chapter 5

# ========== 5.6.1 ==========
stuff = {'rope':1, 'torch':6, 'gold coin':42, 'dagger':1, 'arrow':12}

# 定義一個涵數displayInventory, stuff字典的鍵與值就被帶入參數inventory
def displayInventory(inventory):
    print("Inventory:")

# 先把item_total設為0
    item_total = 0

# 利用多重賦值的技巧, 在for循環中將鍵值賦給k變量, 將值賦給v變量.
    for k, v in inventory.items():
# 印出正整數的值(v)與鍵(k)
        print(str(v) + ' ' + k)
        item_total += v
    print("Total number of items: " + str(item_total))

displayInventory(stuff)

# ========== 5.6.2 ==========

# 定義一個更新物品清單的涵數, 帶有兩個參數,
# 參數inventory就是inv, 參數addedItems就是戰利品清單
def addToInventory(inventory, addedItems):
# 可以拿掉#來顯示for循環會跑幾次
    #print ('len: ', len(addedItems))
    for i in range(len(addedItems)):
# 可以拿掉#來顯示這一次的循環是什麼戰利品
        #print('The added item is: ', addedItems[i])
# 參數inventory, 設一個默認值, 把addedItems帶入, 如果該鍵(addedItems)沒有值就是0
        inventory.setdefault(addedItems[i],0)
# 如果參數inventory, 已經有個addedItems, 就把addedItems加1
        inventory[addedItems[i]] = inventory[addedItems[i]] + 1
# 把戰利品清單(addedItems)都加入inventory後, 就返回inventory的值
    return inventory

# 原本的物品清單
inv = {'gold coin':42, 'rope':1}

# 打完龍後的戰利品清單
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']

# 呼叫addToInventory涵數, 將物品清單與戰利清單總合一下更新
inv = addToInventory(inv, dragonLoot)

# 呼叫displayInventory來展示更新後的物品清單
displayInventory(inv)

然後用Windows的cmd, 執行python.
D:\Tech\Python\Automate The Boring Stuff With Python>python Chapter_5.py
Inventory:
1 rope
6 torch
42 gold coin
1 dagger
12 arrow
Total number of items: 62
Inventory:
45 gold coin
1 rope
1 dagger
1 ruby
Total number of items: 48

D:\Tech\Python\Automate The Boring Stuff With Python>

完成

Reference:
Automate the Boring Stuff with Python
Python編程快速上手--讓繁瑣工作自動化
ISBN-10: B01N6B9BSA
https://www.amazon.com/Python%E7%BC%96%E7%A8%8B%E5%BF%AB%E9%80%9F%E4%B8%8A%E6%89%8B-%E8%AE%A9%E7%B9%81%E7%90%90%E5%B7%A5%E4%BD%9C%E8%87%AA%E5%8A%A8%E5%8C%96-%E7%BE%8E-Al-Sweigart%EF%BC%88%E6%96%AF%E7%BB%B4%E5%8A%A0%E7%89%B9%EF%BC%89/dp/B01I0XN8XY/ref=sr_1_1?ie=UTF8&qid=1543814481&sr=8-1&keywords=9787115422699

官網:
https://automatetheboringstuff.com/

最初發表 / 最後更新: 2018.12.25 / 2018.12.25

0 comments:

張貼留言