第八节课:基本数据结构习题


##习题1:


列表a = [11,22,24,29,30,32]


1 把28插入到列表的末端

a.append(28)

2 在元素29后面插入元素57

>>> a = [11,22,24,29,30,32]
3
>>> a.insert(a.index(29)+1,57)
>>> a
[11, 22, 24, 29, 57, 30, 32]

3 把元素11修改成6

a[0] = 6 
a[a.index(11)] = 6

3 删除元素32

del a[a.index(32)]
del a[5]
a.pop()

 

4 对列表从小到大排序

a.sort() 直接修改原列表

##习题2:


列表b = [1,2,3,4,5]


1 用2种方法输出下面的结果:

[1,2,3,4,5,6,7,8]
方法一:

b.append(6)
b.append(7)
b.append(8)
方法二:
b.insert(len(b),6)
b.insert(len(b),7)
b.insert(len(b),8)
方法三:
b.extend([6,7,8])

b + [6,7,8]

2 用列表的2种方法返回结果:[5,4]

c = b[3:5]
d = c.reverse()
print d

b.reverse()
b[0:2]

print b[-1:-3:-1]

 

3 判断2是否在列表里

2 in b

##习题3:


b = [23,45,22,44,25,66,78]


用列表解析完成下面习题:


1 生成所有奇数组成的列表

[x for x in b if x%2 == 1]

2 输出结果: ['the content 23','the content 45']

('the content %d', 'the content %d') % (b[0],b[1]) 错误 
['the content ' + str(x) for x in b[0:2]] 
['the content %s' % x for x in b[:2]]

 

3 输出结果: [25, 47, 24, 46, 27, 68, 80]

[x+2 for x in b]

##习题4:


用range方法和列表推导的方法生成列表:

[11,22,33]

[x*11 for x in range(1,4)]

 

##习题5:


已知元组:a = (1,4,5,6,7)


1 判断元素4是否在元组里

4 in a

2 把元素5修改成8

b = list(a)
b[2] = 8 
a = tuple(b)

##习题6:

已知集合:setinfo = set('acbdfem')和集合finfo = set('sabcdef')完成下面操作:


1 添加字符串对象'abc'到集合setinfo

setinfo.add('abc')

2 删除集合setinfo里面的成员m

setinfo.remove('m')

3 求2个集合的交集和并集

>>> setinfo&finfo
set(['a', 'c', 'b', 'e', 'd', 'f'])
>>> setinfo | finfo
set(['a', 'c', 'b', 'e', 'd', 'f', 's', 'abc'])

##习题7:


用字典的方式完成下面一个小型的学生管理系统。


1 学生有下面几个属性:姓名,年龄,考试分数包括:语文,数学,英语得分。


比如定义2个同学:


姓名:李明,年龄25,考试分数:语文80,数学75,英语85

姓名:张强,年龄23,考试分数:语文75,数学82,英语78

student_one = {'name':'李明','age':25, 'score':{'yuwen':80,'math':75,'English':85}}
student_two = dict(name='zhangqang', age=23, score = dict(yuwen = 80,math=75,English=85))

2 给学生添加一门python课程成绩,李明60分,张强:80分

student_one['score']['python'] = 60
student_two.update({'score':{'python':80, 'yuwen':80, 'math':75, 'English':85}})

3 把张强的数学成绩由82分改成89分

student_two['score']['math'] = 89

4 删除李明的年龄数据

del student_one['score']['math']

del student_one['age']
student_one.pop['age']

 

5 对张强同学的课程分数按照从低到高排序输出。

scores = student_two['score'].values()
scores.sort()
print scores

6 外部删除学生所在的城市属性,不存在返回字符串 beijing

student_two.pop('city','beijing')
原文地址:https://www.cnblogs.com/huiming/p/5533118.html