Python编程-让繁琐的工作自动化(五)字典和结构化数据【井字棋】

本文围绕Python字典展开,介绍了用花括号、列表或元组、dict关键字三种方式创建字典,阐述了字典的内置函数和方法,如keys()、values()、get()、setdefault()等,还通过井字棋游戏展示了字典的综合运用,包括嵌套使用和for循环访问。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

创建字典

1.用花括号{}语法创建字典

2.通过列表或元组作为参数创建

3.使用dict关键字指定的方式

1.字典的内置函数

2.字典的内置方法

3.字典的常用内置方法实例:

常用方法:keys(),values(),items.

检查字典的键值是否存在get()

setdefault()方法

综合运用:

1.井字棋游戏:

字典的嵌套使用&for循环访问字典


字典是python中唯一的映射类型,采用键值对(key-value)的形式储存数据,python对key进行哈希函数运算,所以key值必须是可哈希的,可哈希表key必须是不可变的,如:数字、字符串、元组,元组的值value可以为所有类型的数据。系统根据哈西的计算结果储存value的地址,所以字典是无序的。
相对于列表,字典是通过键来存取,二列表是通过偏移(下标)来存取。

创建字典

1.用花括号{}语法创建字典

score={'语文':89, '数学':92, '英语':99}

2.通过列表或元组作为参数创建

vwgwtables=[('白菜', 69),('番茄',10),('豆腐',7)]
dict_veg = dict(vwgwtables)
print(dict_veg)

cars = [['BEENS', 10],['BMW',9],['AUDI',8]] 
dict_car = dict(cars)
print(dict_car)

3.使用dict关键字指定的方式

score = dict(语文=92, 数学=89, 英语=92)

以下的表格列举函数来自:菜鸟教程

1.字典的内置函数

序号函数及描述
1cmp(dict1, dict2)
比较两个字典元素。
2len(dict)
计算字典元素个数,即键的总数。
3str(dict)
输出字典可打印的字符串表示。
4type(variable)
返回输入的变量类型,如果变量是字典就返回字典类型。

2.字典的内置方法

序号函数及描述
1dict.clear()
删除字典内所有元素
2dict.copy()
返回一个字典的浅复制
3dict.fromkeys(seq[, val])
创建一个新字典,以序列 seq 中元素做字典的键,val 为字典所有键对应的初始值
4dict.get(key, default=None)
返回指定键的值,如果值不在字典中返回default值
5dict.has_key(key)
如果键在字典dict里返回true,否则返回false
6dict.items()
以列表返回可遍历的(键, 值) 元组数组
7dict.keys()
以列表返回一个字典所有的键
8dict.setdefault(key, default=None)
和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default
9dict.update(dict2)
把字典dict2的键/值对更新到dict里
10dict.values()
以列表返回字典中的所有值
11pop(key[,default])
删除字典给定键 key 所对应的值,返回值为被删除的值。key值必须给出。 否则,返回default值。
12popitem()
随机返回并删除字典中的一对键和值。

 

3.字典的常用内置方法实例:

字典的定义

mycat = {'size':'fat', 'color':'gray', 'disposition':'loud'};
print('mycat discription is:', mycat)
#按键访问值
print("mycat's color is "+ mycat['color'] +',size is '+mycat['size'] + ',disposition is '+mycat['disposition'])

常用方法:keys(),values(),items.

在交互式环境中测试如下结果,注意换行和缩进

#注意,他们的返回值不是列表,且不能被修改
'''
交互式环境中输入以下测试
>>> spam = {'color':'red','age':'42'}
>>> print(spam)
{'color': 'red', 'age': '42'}
>>> for i in spam.values():
... print(i)
  File "<stdin>", line 2
    print(i)
        ^
IndentationError: expected an indented block   #缩进少了,就是这么麻烦又松散又严谨,无语
>>> for i in spam.values():
...     print(i)    ##缩进,4个space或一个tab
...
red
42
>>> for k in spam.keys():
...     print(k)
...
color
age
>>> for t in spam.items():
...     print(t)
...
('color', 'red')
('age', '42')
>>>

一般来说, 调用 items(),keys(),values()方法后,都需要调用list()来将其转换为方便处理的类型

def dic_functions():
    car = {'BMW':8.5, 'BENS':8.3, 'AUDI':8}
    itms = car.items()
    print(itms) #dict_items([('BMW', 8.5), ('BENS', 8.3), ('AUDI', 8)])
    itm_list = list(itms)
    print(itm_list) #[('BMW', 8.5), ('BENS', 8.3), ('AUDI', 8)]
    print(itm_list[1])

    key_list = list(car.keys())
    print(key_list)
    values_list = list(car.values())
    print(values_list)

输出:

dict_items([('BMW', 8.5), ('BENS', 8.3), ('AUDI', 8)])
[('BMW', 8.5), ('BENS', 8.3), ('AUDI', 8)]
('BENS', 8.3)
['BMW', 'BENS', 'AUDI']
[8.5, 8.3, 8]

检查字典的键值是否存在get()

get()方法相当于dict[key]的安全版,当key-value 不存在时不会直接返回错误,而是返回None。

#检查字中的键是否存在——方法get().
#它有两个参数,第一个是要取得其值得键,第二个是键不存在是需要返回的备用值。
'''
#交互式环境
>>> picI = {'apple':5, 'cups':2}
>>> 'I am bringing'+ str(picI.get('cups',0)) + 'cups.'
'I am bringing2cups.'
>>> 'I am bringing '+ str(picI.get('cups',0)) + ' cups.'
'I am bringing 2 cups.'
>>> 'I am bringing '+ str(picI.get('eggs',0)) + ' eggs.'
'I am bringing 0 eggs.'

setdefault()方法

确保一个键不存在时设置该键对应的值

参数:第一个是要检查的键,第二个是如果该键不存在时要设置的值,如果该键存在,就返回键的值

注意,字典的键不可以改变,单可以根据字典的键来修改字典的值

setdefault()方法使用实例:

message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
import pprint #引入专用的打印模块
def CountChar(str):
    cout = {} #空字典
    for char in message:
        cout.setdefault(char, 0) #如果当前不存在该字符键对应的个数,就默认为0,如果存在,就返回其值
        cout[char] += 1 #每次出现一次该字符,就统计到键-值对
    
    pprint.pprint(cout)

CountChar(message)#调用函数

结果像这样:

综合运用:

1.井字棋游戏:

用X和O填入格子,下图不是程序的运行图,代码都是自己根据理解写的,包括一些占位判断,输入错误检查,最先胜利方检查。具体效果大家可以复制到.py文件运行查看

 

#井字棋建模
Braille = {
    'Top-L':' ', 'Top-M':' ', 'Top-R':' ',
    'Mid-L':' ', 'Mid-M':' ', 'Mid-R':' ',
    'Low-L':' ', 'Low-M':' ', 'Low-R':' '
}

def PrintBraille(braille):
    print('The Braille now is:')
    print(braille['Top-L'] + '|' + braille['Top-M'] + '|' + braille['Top-R'])
    print('-+-+-')
    print(braille['Mid-L'] + '|' + braille['Mid-M'] + '|' + braille['Mid-R'])
    print('-+-+-')
    print(braille['Low-L'] + '|' + braille['Low-M'] + '|' + braille['Low-R'])

#PrintBraille(Braille)

def CHeckBraille(braille,count):
    #判断玩家是否赢得棋局
    print('Check Brailles game result')
    if (braille['Top-L'] == braille['Top-M'] == braille['Top-R'] == 'X'
        or braille['Mid-L'] == braille['Mid-M'] == braille['Mid-R'] == 'X'
        or braille['Low-L'] == braille['Low-M'] == braille['Low-R'] == 'X'
        or braille['Top-L'] == braille['Mid-L'] == braille['Low-L'] == 'X'
        or braille['Top-M'] == braille['Mid-M'] == braille['Low-M'] == 'X'
        or braille['Top-R'] == braille['Mid-R'] == braille['Low-R'] == 'X'):
        #print('The Winner is X')
        return 'X'
    elif(braille['Top-L'] == braille['Top-M'] == braille['Top-R'] == 'O'
        or braille['Mid-L'] == braille['Mid-M'] == braille['Mid-R'] == 'O'
        or braille['Low-L'] == braille['Low-M'] == braille['Low-R'] == 'O'
        or braille['Top-L'] == braille['Mid-L'] == braille['Low-L'] == 'O'
        or braille['Top-M'] == braille['Mid-M'] == braille['Low-M'] == 'O'
        or braille['Top-R'] == braille['Mid-R'] == braille['Low-R'] == 'O'):
        #print('The Winner is X')
        return 'O'
    elif count == 8:
        #print('The game ended in a tie.')
        return 'E'
    else:
        return 'C' #既没有玩家赢,棋局也没有结束

def CheckInput(braille, move):
    ocp = 0
    #先检查输入的位置是否在棋盘内
    if move not in braille.keys():
        return -1
    ocp = str(braille.get(move, '0'))#理论上只会返回' ',已有值,这里判断的是其他值
    if ' ' == ocp: #该位置没有占位,允许放置棋子
        return 0
    else:
        return 1

def DoBraille(braille):
    Ret = None
    turn = 'X'
    ocp = -1

    for i in range(9):
        PrintBraille(braille)
        while True:
            print('turn for '+ turn + '. Move on which space?')
            move = input() #默认输入string
            #加上一个占位判断,如果当前位置已有值,那么提示重新选择位置
            ocp = CheckInput(braille,move)
            if 0 == ocp: #该位置没有占位,允许放置棋子
                braille[move] = turn
                break
            elif 1== ocp:
                print('space ' + move +' is already occupied by other piece, please choose space again!')
                continue
            else:   #这里就是输入的键不存在的了
                print('space ' + move +' is not in checkerboard, please choose space again!')
                continue

        if turn == 'X':
            turn = 'O'
        else:
            turn = 'X'
        #当步数多于4步,每次检查棋局结果
        if i >= 4:    #第5步以后检查是否有玩家赢
            Ret = CHeckBraille(braille, i)
            if 'C' == Ret:#继续
                continue
            else:   #游戏结束或者有玩家获胜
                break

    PrintBraille(braille)
    if 'E' == Ret:
        print('The game ended in a tie.')
    else:
        print('The game ended ,Winner is ',Ret)

DoBraille(Braille)

效果类似这样

字典的嵌套使用&for循环访问字典

列出所有类型礼物的数量

#!/usr/bin/python3
#字典的嵌套
#统计聚会所有人带来的礼物的种类和数量
allGuests = {'Alice': {'Apples': 5, 'Pretsels': 12},
            'Bob': {'han sandwiches': 3, 'Apples': 2},
            'Carol':{'cups': 3, 'Potatoe pies': 1}
}

def GetGuestNum(allG, kind):
    gusNum = 0
    for k, v in allG.items():    #返回两个值,键和值,python可以同时返回多个值
        gusNum += v.get(kind, 0)    #指定类型,如果没有,返回0
    return gusNum

def ListAllGuests(allG):
    uniq = {}
    print('Number of Guests list as follow:')
    for k, v in  allG.items():
        for i in v.keys():
            uniq.setdefault(i, 0)
            uniq[i] += 1
            if uniq[i]>1:
                continue    #不打印重复的键值
            print('- ' + i , GetGuestNum(allG, i ))
        
ListAllGuests(allGuests)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值