- 写一个匿名函数,判断指定的年是否是闰年 (先直接用普通函数)
def leap_year(year):
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
print('闰年')
else:
print('平年')
- 写一个函数将一个指定的列表中的元素逆序( 如[1, 2, 3] -> [3, 2, 1])(注意:不要使用列表自带的逆序函数)
def reverse(s):
new = []
s = s[::-1]
return s
s = [1, 2, 3]
print(reverse(s))
- 编写一个函数,计算一个整数的各位数的平方和
例如: sum1(12) -> 5(1的平方加上2的平方) sum1(123) -> 14
def squares_sum(num):
num = str(num)
sum1 = 0
for i in num:
sum1 += int(i)**2
return sum1
print(squares_sum(123))
- 求列表 nums 中绝对值最小的元素
例如:nums = [-23, 100, 89, -56, -234, 123], 最大值是:-23
def min_(nums):
square = nums[0]**2
index = nums[0]
for i in nums[1:]:
n = i**2
if n < square:
square = n
index = nums[i]
return index
nums = [-23, 100, 89, -56, -234, 123]
print(min_(nums))
-
已经两个列表A和B,用map函数创建一个字典,A中的元素是key,B中的元素是value
A = ['name', 'age', 'sex'] B = ['张三', 18, '女'] 新字典: {'name': '张三', 'age': 18, 'sex': '女'}
def dict_(keys, values):
new_dict = {}
for index in range(len(keys)):
new_dict[keys[index]] = values[index]
return new_dict
A = ['name', 'age', 'sex']
B = ['张三', 18, '女']
print(dict_(A, B))
-
已经三个列表分别表示5个学生的姓名、学科和班号,使用map将这个三个列表拼成一个表示每个学生班级信息的的字典
names = ['小明', '小花', '小红', '老王'] nums = ['1906', '1807', '2001', '2004'] subjects = ['python', 'h5', 'java', 'python'] 结果:{'小明': 'python1906', '小花': 'h51807', '小红': 'java2001', '老王': 'python2004'}
def class_(names: list, subject: list, class_num: list):
new_dict = {}
for index in range(len(names)):
new_dict[names[index]] = subjects[index] + class_num[index]
return new_dict
names = ['小明', '小花', '小红', '老王']
nums = ['1906', '1807', '2001', '2004']
subjects = ['python', 'h5', 'java', 'python']
print(class_(names, subjects, nums))
-
已经一个列表message, 使用reduce计算列表中所有数字的和
message = ['你好', 20, '30', 5, 6.89, 'hello'] 结果:31.89
def sum2(list1: list):
sum = 0
for x in list1:
if type(x) in (int, float):
sum += x
return sum
message = ['你好', 20, '30', 5, 6.89, 'hello']
print(sum2(message))
-
已经列表points中保存的是每个点的坐标(坐标是用元组表示的,第一个值是x坐标,第二个值是y坐标)
points = [ (10, 20), (0, 100), (20, 30), (-10, 20), (30, -100) ]
1)获取列表中y坐标最大的点
def y_max(points):
new = []
for i in points:
new.append(i[1])
return max(new)
print(y_max(points))
2)获取列表中x坐标最小的点
def x_min(points):
new = []
for i in points:
new.append(i[0])
return min(new)
print(x_min(points))
3)获取列表中距离原点最远的点
def far_point(points):
max_point = []
num = 0
for i in points:
max1 = i[0]**2+i[1]**2
if max1 > num:
num = max1
return i
print(far_point(points))
4)将点按照点到x轴的距离大小从大到小排序
result = sorted(points, key=lambda x: x[-1] ** 2, reverse=True)
print(result)