5、字典、集合、序列

一、字典
1、字典基本操作

字典内容如下:

dic = {
‘python’: 95,
‘java’: 99,
‘c’: 100
}
用程序解答下面的题目

字典的长度是多少
请修改’java’ 这个key对应的value值为98
删除 c 这个key
增加一个key-value对,key值为 php, value是90
获取所有的key值,存储在列表里
获取所有的value值,存储在列表里
判断 javascript 是否在字典中
获得字典里所有value 的和
获取字典里最大的value
获取字典里最小的value
字典 dic1 = {‘php’: 97}, 将dic1的数据更新到dic中

dic={'python':95,'java':99,'c':100}
print("The length of the dictionary is:" , len(dic))
#The length of the dictionary is:3

dic['java']=98
print(dic)
#{'python':95,'java':98,'c':100}

dic.pop('c')
print(dic)
#{'python':95,'java':98}

dic.setdefault('php',90)
print(dic)
#{'python':95,'java':98,'php':90}

lst1=list(dic.keys())
print(lst1)
#['python','java','php']

lst2=list(dic.values())
print(lst2)
#[95,98,90]

if 'javascrip'in dic:
	print('javascrip is in dic')
else:
    print('javascrip is in not dic')
#javascrip is in not dic

print('The sum of the values is:',sum(lst2))
#The sum of the values is:283

print('The max of the values is:',max(lst2))
#The max of the values is:98

print('The min of the values is:',min(lst2))
#The min of the values is:90

dic1={'php':97}
dic.update(dic1)
print(dic)
#{'python':95,'java':98,'php':97}

2、字典中的value

有一个字典,保存的是学生各个编程语言的成绩,内容如下

data = {
‘python’: {‘上学期’: ‘90’, ‘下学期’: ‘95’},
‘c++’: [‘95’, ‘96’, ‘97’],
‘java’: [{‘月考’:‘90’, ‘期中考试’: ‘94’, ‘期末考试’: ‘98’}]
}
各门课程的考试成绩存储方式并不相同,有的用字典,有的用列表,但是分数都是字符串类型,请实现函数transfer_score(score_dict),将分数修改成int类型

def transfer_score(data):
# your code here

二、集合

1.怎么表示只包含⼀个数字1的元组。

2.创建一个空集合,增加 {‘x’,‘y’,‘z’} 三个元素。

set1=set()
set1.add('x')
set1.add('y')
set1.add('z')
print(set1)
#{'z','y','x'}

3.列表[‘A’, ‘B’, ‘A’, ‘B’]去重。

lst=['A','B','A','B']
lst1=[]
for item in lst:
	if item not in lst1:
		lst1.append(item)
print(lst1)
#['A','B']

4.求两个集合{6, 7, 8},{7, 8, 9}中不重复的元素(差集指的是两个集合交集外的部分)。

a={6,7,8}
b={7,8,9}
c=a.symmetric_difference(b)
print(c)
#(9,6)

5.求{‘A’, ‘B’, ‘C’}中元素在 {‘B’, ‘C’, ‘D’}中出现的次数。

三、序列
1.怎么找出序列中的最⼤、⼩值?
max(sub)返回序列或者参数集合中的最大值;
min(sub)返回序列或参数集合中的最小值

2.sort() 和 sorted() 区别
list.sort()只适用于列表元素的排序。
sorted()适用于所有可迭代对象元素的排序。

3.怎么快速求 1 到 100 所有整数相加之和?

print(sum(range(1,101)))
#5050

4.求列表 [2,3,4,5] 中每个元素的立方根。

5.将[‘x’,‘y’,‘z’] 和 [1,2,3] 转成 [(‘x’,1),(‘y’,2),(‘z’,3)] 的形式。

a=['x','y','z']
b=[1,2,3]
c=zip(a,b)
print(list(c))
#[('x',1),('y',2),('z',3)]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值