python学习12之字典和结构化数据

本文介绍了Python字典的关键特性,如无序的键值对、keys(),values(),items()方法,以及in和notin操作符用于检查键或值的存在。讨论了get()和setdefault()方法来安全地访问和设置字典值。此外,展示了如何计算字符串中字符的出现次数,并使用pprint模块进行整洁的打印。文章还涉及了一个简单的棋盘游戏示例和一个统计物品数量的函数。
摘要由CSDN通过智能技术生成

字典和结构化数据

1.字典中的表项是不排序的,在字典中键值对输入的顺序并不重要

# 如何判断两个字典是否相同
list1 = [1,2,0,9,3]
list2 = [0,9,1,2,3]
print(list1 == list2)

spam = {'name':'Eric', 'spiece':'cat', 'age':'5'}
ham = {'age':'5','name':'Eric','spiece':'cat'}
print(spam == ham)

2.keys()键、values()值、items()键值对方法

这些方法返回的值不是真正的列表,他们不能被修改,所以没有append()方法

spam1 = {'color':'red', 'age':42}
for key in spam1.keys():
    print(key)
print(list(spam1.keys()))
# items()方法返回的是,包含键值对的元组
for key in spam1.items():
    print(key)

3.in, not in 检查字典中是否存在键或值

spam2 = {'name':'zophie', 'age':7}
print( 'eric' in spam2.keys())
print( 7 in spam2.values())

4.get()方法

在访问一个键的值之前,检查该键是否存在于字典中,可以用get()方法。get()方法有两个参数,一个是要取得其值的键,以及如果该键不存在时,返回的备用值

get()方法只能由键找值。找不到,则返回备用值

spam3 = {'name':'zope', 'age':7}
print(spam3.get('names','not existed'))
print(spam3.get('zope','not existed'))

5.setdefault()方法

如果键不存在于字典中,将会添加键并将值设为默认值

spam4 = {'name':'zipe', 'age':7}
print(spam4.setdefault('names','oppo'))

计算字符串中每一个字符出现的次数

message = 'It was a bright cold day in April, and the clocks were striking thirteen'
#print(list(message.strip()))#这里我想用strip()删除字符串中间的字符,但是不行。因为strip()只能删除头尾字符
messages = list(message)
print(messages)
# k = ' '
# for i in messages:#清除list中的空格
#     if i == k:
#         messages.remove(i)
# print(messages)
abbreviation = []
for i in messages:
    if i == ' ':
        abbreviation.append(i)
    elif i.lower() not in abbreviation:
        abbreviation.append(i.lower())
print(abbreviation)
dic1 = {}
for i in abbreviation:
    count = 0
    for j in range(len(messages)):
        if messages[j] == i:
            count += 1
    dic1[i] = count
print(dic1)

# 简单做法!!!!
count = {}
for character in message:
    count.setdefault(character, 0)
    count[character] = count[character] + 1
print(count)

6.漂亮的打印

如果程序中导入pprint模块,就可以使用pprint()和pformat()函数。这比print()打印的更干净。键排过序

若字典中本身包含嵌套的列表或字典,pprint.pprint()函数就特别有用

import pprint
pprint.pprint(count)
# 如果希望得到打印的干净文本作为字符串,而不是显示在屏幕上,就调用pprint.pformat()
print(pprint.pformat(count))

代数记谱法描述棋盘中的

# top-l | top-m | top-r
# ---------------------
# mid-l | mid-m | mid-r
# ---------------------
# low-l | low-m | low-r
theBoard = {'top-l': ' ','top-m': ' ','top-r': ' ',
            'mid-l': ' ','mid-m': ' ','mid-r': ' ',
            'low-l': ' ','low-m': ' ','low-r': ' ',
            }
def printBoard(board):
    print(' ' + theBoard['top-l'] + ' | ' + theBoard['top-m'] + ' | ' + theBoard['top-r'])
    print("-----------")
    print(' ' + theBoard['mid-l'] + ' | ' + theBoard['mid-m'] + ' | ' + theBoard['mid-r'])
    print("-----------")
    print(' ' + theBoard['low-l'] + ' | ' + theBoard['low-m'] + ' | ' + theBoard['low-r'])
printBoard(theBoard)

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)


allGuests = {
    'Alice':{'apples':5, 'pertzels':12},
    'Bob':{'ham sandwiches':3, 'apples':2},
    'Carol':{'cups':3, 'apple pies':1},
}
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')))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值