Python 3 教程 在线

1078Python3 字典

用字典记录学生名字和分数,再分级:

#!/usr/bin/python3

students= {}
write = 1
while write :
    name = str(input('输入名字:'))
    grade = int(input('输入分数:'))
    students[str(name)] = grade
    write= int(input('继续输入?\n 1/继续  0/退出'))
print('name  rate'.center(20,'-'))
for key,value in students.items():
    if value >= 90:
        print('%s %s  A'.center(20,'-')%(key,value))
    elif 89 > value >= 60 :
        print('%s %s  B'.center(20,'-')%(key,value))
    else:
        print('%s %s  C'.center(20,'-')%(key,value))

测试输出结果:

输入名字:a
输入分数:98
继续输入?
 1/继续  0/退出1
输入名字:b
输入分数:23
继续输入?
 1/继续  0/退出0
-----name  rate-----
------a 98  A------
------b 23  C------

1077Python3 字典

字典是支持无限极嵌套的,如下面代码:

cities={
    '北京':{
        '朝阳':['国贸','CBD','天阶','我爱我家','链接地产'],
        '海淀':['圆明园','苏州街','中关村','北京大学'],
        '昌平':['沙河','南口','小汤山',],
        '怀柔':['桃花','梅花','大山'],
        '密云':['密云A','密云B','密云C']
    },
    '河北':{
        '石家庄':['石家庄A','石家庄B','石家庄C','石家庄D','石家庄E'],
        '张家口':['张家口A','张家口B','张家口C'],
        '承德':['承德A','承德B','承德C','承德D']
    }
}

可以使用如下方法进行列出

for i in cities['北京']:
    print(i)

将列出如下结果:

朝阳
海淀
昌平
怀柔
密云
for i in cities['北京']['海淀']:
    print(i)

输出如下结果:

圆明园
苏州街
中关村
北京大学

1076Python3 字典

字典的键值是"只读"的,所以不能对键和值分别进行初始化,即以下定义是错的:

>>> dic = {}
>>> dic.keys = (1,2,3,4,5,6)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'dict' object attribute 'keys' is read-only
>>> dic.values = ("a","b","c","d","e","f")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'dict' object attribute 'values' is read-only
>>> 

1075Python3 元组

关于如何修改元组的几个脱裤子放屁的方法:

# 方法一,赋值修改法
tup = (4,5,6,7,8) 
tup = ('谁', '说', '元', '组', '不', '能', '改')
print(tup)
#输出: ('谁', '说', '元', '组', '不', '能', '改')


#方法二、中间变量法
tup = (4, 6, 7,8, 9, 10 ,0)
tup = list(tup)
list2 = ['谁', '说', '元', '组', '不', '能', '改']
for i in range(7):
    tup[i] = list2[i]
print(tup)
#输出: ['谁', '说', '元', '组', '不', '能', '改']

1074Python3 元组

通过间接方法修改元组:

tuple1 = (1,2,4,5)
tuple2 = tuple1[:2] + (3,) + tuple1[2:]
print(tuple2)

输出结果为:

(1, 2, 3, 4, 5)