Dictionary Example

Dictionary 範例

我們透過範例來學習dictionary的一些實際操作。

範例一

import pprint

text = 'Welcome to the LearnPython.org interactive Python tutorial. ' \
       'Whether you are an experienced programmer or not, ' \
       'this website is intended for everyone who wishes to learn the Python programming language. ' \
       'You are welcome to join our group on Facebook for questions, discussions and updates. ' \
       'Just click on the chapter you wish to begin from, and follow the instructions. Good luck!'
       
counts = {}

for char in text:
    counts.setdefault(char, 0)
    counts[char] = counts[char] + 1

pprint.pprint(counts)

這個範例的text可以存放任何長度的文章,然後找出每個字元出現的次數,是個有趣的統計,你可以看看哪個英文字母被使用最多次。

另外,這邊也使用了pprint模組,可以將dictionary以比較好閱讀的形式打印出來。

範例二

gameBoard = {'top-left': ' ', 'top-mid': ' ', 'top-right': ' ',
             'mid-left': ' ', 'mid-mid': ' ', 'mid-right': ' ',
             'bottom-left': ' ', 'bottom-mid': ' ', 'bottom-right': ' '}

def printBoard(board):
    print('{}|{}|{}'.format(board['top-left'], board['top-mid'], board['top-right']))
    print('-+-+-')
    print('{}|{}|{}'.format(board['mid-left'], board['mid-mid'], board['mid-right']))
    print('-+-+-')
    print('{}|{}|{}'.format(board['bottom-left'], board['bottom-mid'], board['bottom-right']))

for i in range(9):
    if i % 2 == 0:
        print('It is O turn. Please enter which position you wanna put: ')
        pos = input()
        gameBoard[pos] = 'O'
    else:
        print('It is X turn. Please enter which position you wanna put: ')
        pos = input()
        gameBoard[pos] = 'X'
    printBoard(gameBoard)

這個範例則是做出了大家熟知的井字遊戲,由O先攻,再換X,可以理解使用dictionary可以為真實世界的很多種狀況建模,是個非常好用的工具。

然而這個範例並沒有做出驗證誰已經勝利的程式,所以大家可以自己來試看看如何檢驗勝利,並且在勝利條件產生時,直接跳出。

Last updated

Was this helpful?