Python学习--5、6

5-字典

字典–{键:值}

birth={'psc':'8.10','hl':'5.28','wx':'3.7'} 
while True:
    print('Enter the name:')
    name=input()
    if name=='':
        break
    if name in birth:
        print(birth[name]+' is the birth '+name)
    else:
        print('No record')
        print('What is your birthday?')
        bday=input() #程序终止时,更新的数据丢失,字典数据保持原样
        birth[name]=bday
        print('Updated.')
>>> 
Enter the name:
hl
5.28 is the birth hl
Enter the name:
ps
No record
What is your birthday?
'2.4'
Updated.
Enter the name:
ps
'2.4' is the birth ps
Enter the name:

字典方法

>>> birth={'psc':'8.10','hl':'5.28','wx':'3.7'}
>>> print(birth[a])
8.10
#keys(),values(),items()返回类似于列表的值,但不是列表,他的值不可变
# dict_keys、dict_values、dict_items可用于for循环
>>> print(birth.keys())
dict_keys(['psc', 'hl', 'wx'])
>>> print(birth.values ()) 
dict_values(['8.10', '5.28', '3.7'])
>>> print(birth.items())
dict_items([('psc', '8.10'), ('hl', '5.28'), ('wx', '3.7')])
>>> for i in birth.items(): #返回的是包含键-值的元组
	print(i)
	
('psc', '8.10')
('hl', '5.28')
('wx', '3.7')
#list()返回列表
>>> list(birth.items()) 
[('psc', '8.10'), ('hl', '5.28'), ('wx', '3.7')]
>>> list(birth)
['psc', 'hl', 'wx']
>>> list(birth.keys())
['psc', 'hl', 'wx']
# 多重赋值
>>> for i,j in birth.items():
	print(j+' is the birthday of '+i+'.')

	
8.10 is the birthday of psc.
5.28 is the birthday of hl.
3.7 is the birthday of wx.
# get()检查该键是否存在于字典中,存在则显示内容,不存在则显示0或None.
# 若不存在该键且无get() 函数,则显示错误。
>>> str(birth.get('psc'))+' is the birthday of sb.'
'8.10 is the birthday of sb.'
>>> str(birth.get('ps'))+' is the birthday of sb.'
'None is the birthday of sb.'
>>> str(birth['ps'])+' is the birthday of sb.'
Traceback (most recent call last):
  File "<pyshell#34>", line 1, in <module>
    str(birth['ps'])+' is the birthday of sb.'
KeyError: 'ps'
# setdefault() 为字典中某个键设置一个默认值,重复设置系统只认第一次设置值
>>> birth.setdefault('ps','5.20');birth
'5.20'
{'psc': '8.10', 'hl': '5.28', 'wx': '3.7', 'ps': '5.20'}
>>> birth.setdefault('ps','6.18');birth
'5.20'
{'psc': '8.10', 'hl': '5.28', 'wx': '3.7', 'ps': '5.20'}
import pprint
psc='He is a responsible and humour person.'
count={}
for word in psc:
    count.setdefault(word,0)
    count[word]=count[word]+1
print(count)
#pprint()打印美观:键排过序
pprint.pprint(count)
#打印的文本作为字符串,不显示在屏幕上
pprint.pformat(count)
print("")
#和pprint.pprint(count)等价
print(pprint.pformat(count))
>>> 
{'H': 1, 'e': 4, ' ': 6, 'i': 2, 's': 4, 'a': 2, 'r': 3, 'p': 2, 'o': 3, 'n': 3, 'b': 1, 'l': 1, 'd': 1, 'h': 1, 'u': 2, 'm': 1, '.': 1}
{' ': 6,
 '.': 1,
 'H': 1,
 'a': 2,
 'b': 1,
 'd': 1,
 'e': 4,
 'h': 1,
 'i': 2,
 'l': 1,
 'm': 1,
 'n': 3,
 'o': 3,
 'p': 2,
 'r': 3,
 's': 4,
 'u': 2}

{' ': 6,
 '.': 1,
 'H': 1,
 'a': 2,
 'b': 1,
 'd': 1,
 'e': 4,
 'h': 1,
 'i': 2,
 'l': 1,
 'm': 1,
 'n': 3,
 'o': 3,
 'p': 2,
 'r': 3,
 's': 4,
 'u': 2}
board={'a11':' ','a12':' ','a13':' ',
       'a21':' ','a22':' ','a23':' ',
       'a31':' ','a32':' ','a33':' '}
def printboard(b):
    print(b['a11']+'|'+b['a12']+'|'+b['a13'])
    print('-+-+-')
    print(b['a21']+'|'+b['a22']+'|'+b['a23'])
    print('-+-+-')
    print(b['a31']+'|'+b['a32']+'|'+b['a33'])
turn='X'
for i in range(9):
    printboard(board)
    print('Turn for '+turn+'. move on which place?')
    move=input()
    board[move]=turn
    if turn=='X':
        turn='0'
    else:
        turn='X'
printboard(board)
>>> 
 | | 
-+-+-
 | | 
-+-+-
 | | 
--snip--
(a22,a12,a31,a13,a11,a33,a23,a21,a32)
X|0|0
-+-+-
0|X|X
-+-+-
X|X|0
#计数
all={'psc':{'apples':5,'cups':3},
     'ps':{'cups':2,'ham sandwishes':6},
     'hl':{'apples':3,'pies':9}}
def totalbrought(guy,item):
    brought=0
    for i,j in all.items():
        brought=brought+j.get(item,0)
    return brought
print('Number of being brought:')
print('apples: '+str(totalbrought(all,'apples')))
print('cups: '+str(totalbrought(all,'cups')))
print('ham sandwishes: '+str(totalbrought(all,'ham sandwishes')))
print('pies: '+str(totalbrought(all,'pies')))
print('cakes: '+str(totalbrought(all,'cakes')))
Number of being brought:
apples: 8
cups: 5
ham sandwishes: 6
pies: 9
cakes: 0

5.6

#5.6.1物品清单
all={'rope':1,'torch':6,'gold coin':42,'dagger':1,'arrow':12}
def numdisplay(tool):
    print('Inventory:')
    play=0
    for i,j in tool.items():
        print(str(j)+' '+i)
        play=play+j
    print('Total number is: '+str(play))
numdisplay(all)
Inventory:
1 rope
6 torch
42 gold coin
1 dagger
12 arrow
Total number is: 62
# 5.6.2
def numdisplay(tool):
    print('Inventory:')
    play=0
    for i,j in tool.items():
        print(str(j)+' '+i)
        play=play+j
    print('Total number is: '+str(play))
    
def addtoinventory(inventory,addeditems):
    for i in range(0,len(addeditems)):
        if addeditems[i] in inventory.keys():
            inventory[addeditems[i]]+=1
    return inventory
    
all={'rope':1,'torch':6,'gold coin':42,'dagger':1,'arrow':12}
loot=['gold coin','dagger','gold coin','gold coin','ruby']
all=addtoinventory(all,loot)
numdisplay(all)
>>> 
Inventory:
1 rope
6 torch
45 gold coin
2 dagger
12 arrow
Total number is: 66

6-字符串操作

字符串:双引号内可加单引号

转义字符含义
单引号
"双引号
\t制表符
\n换行符
\倒斜杠
r+字符串原始字符串(忽略所以转义字符)
"’'三重单引号’内所有引号、制表符或换行都被认为是字符串的一部分
" " "多行注释(注释内容所有引号、制表符或换行都被认可)

注:字符串下标和切片(与列表相似),字符串中每个字符都是一个表项,字符计数包括空格和标点符号。

方法

# upper() 转化为大写字母,非字母字符不变,不改变字符串本身
# lower() 转化为小写字母,非字母字符不变,不改变字符串本身
>>> psc='Hello World.'
>>> psc.upper()
'HELLO WORLD.'
>>> psc.lower()
'hello world.'
>>> psc
'Hello World.'
# isupper/islower 判断字符串是否全是大/小写,返回布尔值
>>> psc.islower()
False
# upper/lower/isupper/islower存在调用链
>>> psc.upper().lower().islower()
True
# isX 都是返回布尔值
# isalpha() 字符串只包含字母,且非空
# isalnum() 字符串只包含数字和字母,且非空
# isdecima() 字符串只包含数字,且非空
# isspace() 字符串只包含空格、制表符和换行,且非空
# istitle() 字符串仅包含大写字母开头,后面但是小写字母的单词
>>> psc.istitle()
True
# startswith()、endswith()返回布尔值,判断是否以该字符串开始或者结束
>>> 'hello world.'.startswith('hello')
True
# '分隔符'.join(字符串列表)-连接字符串列表形成单独的字符串
>>> '.and.'.join(['psc','hl'])
'psc.and.hl'
# '字符串'.split()-将字符串分割成列表,默认为空格,也可在括号中加入分割内容,但分割内容不被包含
>>> 'psclvandlvhl'.split('lv')
['psc', 'and', 'hl']
# 空白字符包括空格、制表符和换行
# strip/lstrip/rstrip 删除空白字符
>>> ' psc is hundan '.strip()
'psc is hundan'
# rjust(字符串长度,指定填充字符)-右对齐
# ljust()-左对齐
# center()-居中
def printitems(item,lwidth,rwidth):
    print('PICNIC ITEMS'.center(lwidth+rwidth,'='))
    for i,j in item.items():
        print(i.ljust(lwidth,'.')+str(j).rjust(rwidth))
all={'rope':1,'torch':6,'gold coin':42,'dagger':1,'arrow':12}
printitems(all,15,5)
>>> 
====PICNIC ITEMS====
rope...........    1
torch..........    6
gold coin......   42
dagger.........    1
arrow..........   12

习题6.7

table=[['apples','oranges','cherries','banana'],
       ['Alice','Bob','Carol','David'],
       ['dogs','cats','moose','goose']]    
def tabledata(spam):
    cwidth=[0]*len(spam)
    for a in range(len(spam)):
        for b in range(len(spam[0])):
            if len(spam[a][b]) > cwidth[a]:
                cwidth[a]=len(spam[a][b])
    for c in range(0,len(spam[0])):
        for r in range(0,len(spam)):
            print(spam[r][c].rjust(cwidth[r])+' ',end='')
        print("")
print('spam1:')   
spam1=tabledata(table)   
>>> #结果
spam1:
  apples Alice  dogs 
 oranges   Bob  cats 
cherries Carol moose 
  banana David goose 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值