技巧
键:'字符串'、整型
值:' '(不管是什么,都要带单引号)
字典中的项不排序:①不可以切片。②只要内容相等,两个字典就相等
方法
从键盘输入字典(in 、not in )
my_friends = {}
while True:
print('输入朋友的姓名,什么都不输入则退出')
name = input()
if name == '':
break
print('输入朋友的生日')
bth = input()
if name not in my_friends:
my_friends[name] = bth
print(my_friends)
keys()
# 返回的是元组
spam = {'color': 'red', 'age': 42}
print('输出字典的键')
print(spam.keys())
values()
# 返回的是元组
spam = {'color': 'red', 'age': 42}
print('输出字典的值')
print(spam.values())
items()
# 返回的是元组
spam = {'color': 'red', 'age': 42}
print('输出字典的键和值')
print(spam.items())
get()
spam = {'color': 'red', 'age': 42}
print('原字典', spam)
print('已知键,得到对应的值')
print('第一个参数:键')
print('第二个参数:键不存在时,默认返回的值')
print(spam.get('color', 'blue'))
print(spam.get('number', '0'))
print('新字典', spam)
setdefault()
spam = {'color': 'red', 'age': 42}
print('原字典', spam)
print('可以确保字典中有一个键存在')
print('第一个参数:键')
print('第二个参数:键不存在时,默认设置的值')
print(spam.setdefault('color', 'blue'))
print(spam.setdefault('number', '0'))
print('新字典', spam)
get()和setdefault()的区别:
setdefault()
除了获取值外,还有添加键值对的功能,而 get()
只是获取值,并且在键不存在时返回默认值。
pprint()、pformat()
import 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] += 1
print('方式1:不美观的写法')
print(count)
print('方式2:打印更美观,而且可以排序。如果字典本身包含嵌套的列表或字典,则更适用')
pprint.pprint(count)
print('方式3:pprint.pformat(count)没有输出功能(除此之外等价于方式2),只是转换为字符串')
pprint.pformat(count)
井字棋
# 1、存储棋盘
theBoard = {'top_L': '', 'top_M': '', 'top_R': '',
'mid_L': '', 'mid_M': '', 'mid_R': '',
'low_L': '', 'low_M': '', 'low_R': ''}
# 2、输出棋盘
def print_board(board):
print(f"{theBoard['top_L']} | {theBoard['top_M']} | {theBoard['top_R']}")
print("--+------+---")
print(f"{theBoard['mid_L']} | {theBoard['mid_M']} | {theBoard['mid_R']}")
print("--+------+---")
print(f"{theBoard['low_L']} | {theBoard['low_M']} | {theBoard['low_R']}")
# print_board(theBoard)
# 3、让玩家输入移动的位置,并且更换玩家
turn = 'X'
print_board(theBoard)
for i in range(9):
print('现在是玩家', turn)
print('请输入你要下棋的位置')
move = input()
theBoard[move] = turn
if turn == 'X':
turn = 'O'
else:
turn = 'X'
print_board(theBoard)
国际象棋验证器
# 棋盘验证器
"""
版本 1 :直接使用列表
问题:判断棋子是否重复,遍历时,自己跟自己重复
def is_valid_chess_board(player):
flag = True
for k, v in chess.items():
v_index=chess.index(v)
for value1 in chess.values():
if v == 'bqueen' and value1 == 'bking':
flag = False
print('黑王白王只能有一个')
if v == 'wqueen' and value1 == 'wking':
flag = False
print('黑王白王只能有一个')
if v == value1:
print('棋子重复')
flag = False
if k not in place:
print('棋子位置错误')
flag = False
if v not in chess_def:
print('棋子名称错误')
flag = False
return flag
"""
"""
版本2 对棋盘理解错误
def is_valid_chess_board(chess):
flag = True
keys_def = []
values_def = []
black_king = 0
white_king = 0
w_count=0
b_count=0
for k, v in chess.items():
keys_def = keys_def.append(k)
values_def = values_def.append(v)
for item in keys_def:
if item not in place:
print('棋子位置错误')
flag = False
for item in values_def:
if item == 'bqueen' or item == 'bking':
black_king += 1
if item == 'wqueen' or item == 'wking':
white_king += 1
if black > 1 or white > 1:
print('黑王,白王只能有一个')
if item.startswith('w'):
w_count+=1
for item1 in values_def:
index_now1 = values_def.index(item1)
for item2 in values_def:
index_now2 = values_def.index(item2)
if item1==item2 and index_now1 != index_now2:
print('')
"""
"""
规则
1、只有一个黑王,一个白王
2、每个玩家最多 16 个棋子,最多 8 个兵
3、有效位置:1a-8h
4、棋子开头w,b代表白和黑。然后是 pawn,knight,bishop,rook,queen,king
"""
def is_valid_chess_board(chess):
keys_def = []
values_def = []
white_chess = []
black_chess = []
wpawn_num = 0
bpawn_num = 0
flag = True
# 字典转换为列表
for k, v in chess.items():
keys_def.append(k)
values_def.append(v)
for item in keys_def:
if item not in place:
flag = False
print('请输入正确的棋子位置')
# 将棋子分别存储到黑棋列表和白棋列表
for item in values_def:
if item.startswith('w'):
white_chess.append(item)
if item.startswith('b'):
black_chess.append(item)
# 判断棋子数量
if len(white_chess) > 16 or len(black_chess) > 16:
print('每位玩家棋子数量不能超过16个')
flag = False
# 针对白棋列表:王、兵
j = 0
for item1 in white_chess:
j += 1
for item2 in white_chess[j + 1:]:
item2_index = white_chess.index(item2)
if item1 == item2 == 'wking':
print('白王只能有一个')
flag = False
if item1 == 'wpawn':
wpawn_num += 1
if wpawn_num > 8:
print('兵最多只能有8个')
flag = False
i = 0
for b_item1 in black_chess:
i += 1
if b_item1 == 'bking':
for b_item2 in black_chess[i + 1:]:
if b_item1 == b_item2:
print('黑王只能有一个')
flag = False
break
if b_item1 == 'bpawn':
bpawn_num += 1
if bpawn_num > 8:
print('兵最多只能有8个')
flag = False
if flag:
print('棋盘无误')
else:
print('棋盘有误')
# chess = {'1h': 'bking', '6c': 'wqueen', '2g': 'bbishop', '5h': 'bqueen', '3e': 'wking','1b':'wpawn'}
chess = {'1h': 'bking', '6c': 'wqueen', '2g': 'bbishop', '5h': 'bqueen', '3e': 'wking', '1b': 'wpawn', '2h': 'bking'}
place = ['1a', '2a', '3a', '4a', '5a', '6a', '7a', '8a',
'1b', '2b', '3b', '4b', '5b', '6b', '7b', '8b',
'1c', '2c', '3c', '4c', '5c', '6c', '7c', '8c',
'1d', '2d', '3d', '4d', '5d', '6d', '7d', '8d',
'1e', '2e', '3e', '4e', '5e', '6e', '7e', '8e',
'1f', '2f', '3f', '4f', '5f', '6f', '7f', '8f',
'1g', '2g', '3g', '4g', '5g', '6g', '7g', '8g',
'1h', '2h', '3h', '4h', '5h', '6h', '7h', '8h']
chess_def = ['bpawn', 'wpawn', 'bknight', 'wknight', 'bbishop', 'wbishop', 'brook', 'wrook', 'bqueen', 'wqueen',
'bking', 'wking']
is_valid_chess_board(chess)
"""
测试
1、兵的数量----------------------------------------
chess = {'1h': 'bking', '6c': 'wqueen', '2g': 'bbishop',
'5h': 'bqueen', '3e': 'wking','1b':'wpawn','1c':'wpawn',
'1d':'wpawn','1e':'wpawn','1a':'wpawn','1f':'wpawn','1g':'wpawn','2h'='wpawn','3h'='wpawn'}
2、王的数量
chess = {'1h': 'bking', '6c': 'wqueen', '2g': 'bbishop', '5h': 'bqueen', '3e': 'wking','1b':'wpawn','2h':'bking'}
3、棋子数量
chess = {'1h': 'bking', '6c': 'wqueen', '2g': 'bbishop', '5h': 'bqueen', '3e': 'wking','1b':'wpawn','1c':'wpawn',
'1d':'wpawn','1e':'wpawn','1a':'wpawn','1f':'wpawn','1g':'wpawn','2h'='wpawn'}
4、棋子位置
chess = {'1h': 'bking', '11c': 'wqueen', '2g': 'bbishop', '5h': 'bqueen', '3e': 'wking','1b':'wpawn'}
"""
好玩游戏的物品清单
# 好玩游戏的物品清单
stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
def display_inventory(inventory):
print('Inventory:')
item_total = 0
for k, v in inventory.items():
item_total = item_total + v
print(str(v) + ' ' + k)
print('total number of items' + ' ' + str(item_total))
display_inventory(stuff)
列表到字典的函数,针对好玩游戏的物品清单
# 好玩游戏的物品清单
def display_inventory(inventory):
print('Inventory:')
item_total = 0
for k, v in inventory.items():
item_total = item_total + v
print(str(v) + ' ' + k)
print('total number of items' + ' ' + str(item_total))
def add_to_inventory(inventory, added_items):
for item in added_items:
if item not in inventory.keys():
inventory[item] = 1
else:
inventory[item] += 1
return inventory
# stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
inv = {'gold coin': 42, 'rope': 1}
dragon_loot = ['gold coin', 'dagger', 'gold coin','gold coin', 'ruby']
inv = add_to_inventory(inv, dragon_loot)
display_inventory(inv)