4/8作业
1、 有两个列表,[2,5,7,8,22,32], [2,5,6,18,32] 把不相同的部分做一个列表并打印
答:
def ass1(list1, list2):
set1 = set(list1)
set2 = set(list2)
list3 = list(set1 ^ set2)
return list3
list1 = [2, 5, 7, 8, 22, 32]
list2 = [2, 5, 6, 18, 32]
print(ass1(list1, list2))
[18, 6, 7, 8, 22]
Process finished with exit code 0
2、 有两个列表,[1,2,3,7], [2,3,4,5,6],合并成一个列表并升序排序
答:
def ass2(list1, list2):
list1.extend(list2)
list1.sort()
return list1
list1 = [1, 2, 3, 7]
list2 = [2, 3, 4, 5, 6]
print(ass2(list1, list2))
[1, 2, 2, 3, 3, 4, 5, 6, 7]
Process finished with exit code 0
3、 编写一个函数,完成功能,传递一个列表,能输出列表的最大值
答:
def testlist(testlist):
list1 = testlist
a = max(list1)
return a
list2 = [1, 34, 22, 0, 90]
print(testlist(list2))
90
Process finished with exit code 0
4、 编写一个函数,完成功能,传递一个列表,把列表首尾下标的值进行调换
答:
def ass4(list1):
list1[0], list1[len(list1) - 1] = list1[len(list1) - 1], list1[0]
# return list1
list1 = [2, 3, 4, 5, 6]
print(ass4(list1))
[6, 3, 4, 5, 2]
Process finished with exit code 0
5、有好友列表[(‘Owen’, ‘上海’), (‘Zero’, ‘上海’), (‘Nick’, ‘安徽’), (‘Jason’, ‘安徽’), (‘Jerry’, ‘江苏’)],
计算每个地区好友的个数,如上列好友列表的结果:{‘上海’: 2, ‘安徽’: 2, ‘江苏’: 1}
答:
def ass5(list1):
dict1 = dict(list1)
# print(dict1)
list2 = list(dict1.values())
# print(list2)
list3 = list(set(list2))
dict3 = {}
for i in range(0, len(list3)):
dict2 = dict(((list3[i], list2.count(list3[i])), ))
dict3.update(dict2)
print(dict3)
list1 = [('Owen', '上海'), ('Zero', '上海'), ('Nick', '安徽'), ('Jason', '安徽'), ('Jerry', '江苏')]
ass5(list1)
{'江苏': 1, '上海': 2, '安徽': 2}
Process finished with exit code 0
6、编写一个函数求规定范围内所有的水仙花数,如果用户输入的值是大于1000,则提示用户只能输入1000以内的数字
科普:水仙花表示三位数 abc = aaa + bbb + ccc
答:
def ass7(i):
i = int(i)
if 100 <= i < 1000:
for j in range(100, i+1):
# 百位a,十位b,个位c
a, b, c = j // 100, j % 100 // 10, j % 10
if j == a**3 + b**3 + c**3:
print('水仙花数:%d' % j)
else:
j += 1
else:
print('请输入100-1000以内的数字')
i = input('请输入一个三位数,我们将返回100到这个数之间的所有水仙花数\n')
ass7(i)
请输入一个三位数,我们将返回100到这个数之间的所有水仙花数
999
水仙花数:153
水仙花数:370
水仙花数:371
水仙花数:407
Process finished with exit code 0
7、用循环嵌套的方式求 1!+ 2!+ … + 10!
答:
for i in range(1, 11):
sum = 1
sum1 = 0
for j in range(1, i+1):
sum *= j
sum1 += sum
# print(sum1)
print(sum1)
4037913
Process finished with exit code 0
8、自定义一个函数,用来生成字典数据
def ass8(*a, **b):
print(a)
print(b)
ass8(1,2,3, a='1',b='2',c='3')
(1, 2, 3)
{'a': '1', 'b': '2', 'c': '3'}
Process finished with exit code 0