1. 写一个匿名函数,判断指定的年是否是闰年
years = lambda x: print('闰年', x) if x % 4 == 0 or x % 100 == 0 else print('不是闰年', x)
years(1999) # 不是闰年 1999
2. 写一个函数将一个指定的列表中的元素逆序( 如[1, 2, 3] -> [3, 2, 1])(注意:不要使用列表自带的逆序函数)
def reverse_wh(list1):
list2 = []
for item in list1[::-1]:
list2 += [item]
print(list2)
reverse_wh([1, 2, 3]) # [3, 2, 1]
3. 写一个函数,获取指定列表中指定元素的下标(如果指定元素有多个,将每个元素的下标都返回) 例如: 列表是:[1, 3, 4, 1] ,元素是1, 返回:0,3
def index_wh(list2:list, n):
for index in range(len(list2)):
if n == list2[index]:
print(index, end=' ')
index_wh([1, 2, 4, 5, 6, 1, 1], 1) # 0 5 6
4. 写一个函数,能够将一个字典中的键值对添加到另外一个字典中(不使用字典自带的update方法)
def dict_wh(dict2: dict, dict3: dict):
for key in dict3:
dict2.setdefault(key, dict3[key])
return dict2
print(dict_wh({'a': 1, 'b': 2}, {'c': 3, 'd': 4}))
5. 写一个函数,能够将指定字符串中的所有的小写字母转换成大写字母;所有的大写字母转换成小写字母(不能使用字符串相关方法)
def change_wh(str1):
list1 = list(str1)
for index in range(len(list1)):
if 'a' <= list1[index] <= 'z':
list1[index] = chr(ord(list1[index])-32)
elif 'A' <= list1[index] <= 'Z':
list1[index] = chr(ord(list1[index])+32)
else:
list1[index] = list1[index]
return str(list1)
print(change_wh('adWADFf23431sw')) # ['A', 'D', 'w', 'a', 'd', 'f', 'F', '2', '3', '4', '3', '1', 'S', 'W']