Day10-Python-作业-2019/01/05

""""""

1.写一个函数将一个指定的列表中的元素逆序(如[1,2,3]->[3,2,1])(注意:不要使用自带的逆序函数)

def my_sort(iterable,key=None,reverse=False):
for index1 in range(len(iterable)-1):
for index2 in range(index1+1,len(iterable)):
if index1 < index2:
iterable[index1], iterable[index2] = iterable[index2], iterable[index1]

    return iterable

print(my_sort([1, 2 ,3, 0, 'a', 12]))

2.写一个函数,提取出字符串中所有奇数位上的字符

def my_get(str1:str):
list1 = []
for index in range(1, len(str1), 2):
list1.append(str1[index])

return list1

print(my_get('asdjkfcsa'))

list2 = [1,21, 31, 12, 99, 0]
print(sorted(list2))

3.写一个匿名函数,判断指定的年是否是闰年

leap_year = lambda x:(x % 4 == 0 and x % 100 != 0) or (x % 400 == 0)
print(leap_year(3000))

5.写函数,提取字符串中所有的数字字符

def get_num(str1:str):
list1 = []
for item in str1:
if '0' < item < '9':
list1.append(item)

return ''.join(list1)

print(get_num('jj3214jsd213'),type(get_num('jj3214jsd213')))

6.写一个函数,获取列表中的成绩的平均值,和最高分

def get_score(list1:list):
sum1 = 0
count = 0
for score in list1:
sum1 += score
count += 1
for index1 in range(len(list1)-1):
for index2 in range(index1+1, len(list1)):
if list1[index1] < list1[index2]:
list1[index1], list1[index2] = list1[index2], list1[index1]

return sum1/count, list1[0]

print(get_score([80, 90, 95, 99, 71, 69]))

7.写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新的列表返回给调用者。

def my_check(iterable):
list1 = []
for index in range(1, len(iterable), 2):
list1.append(iterable[index])

return list1

print(my_check([0, 1, 2, 3, 4, 5]))
print(my_check((0, 1, 2, 3, 4, 5)))

8.实现属于自己的字典update方法:用一个字典去更新另一个字典的元素(不能使用自带的update方法)

def my_update(dict1, dict2):

for key1 in dict1:

for key2 in dict2:

if key1 == key2:

dict1[key1] = dict2[key2]

if key2 not in dict1:

dict1[key2] = dict2[key2]

return dict1

print(my_update({'a':1, 'b':2, 'c':3}, {'a':0, 'e':4})) RuntimeError: dictionary changed size during iteration

9.实现属于自己的items方法:将字典转换成列表,字典中的键值对转换成元组。(不能使用items方法)

例如:{'a': 1, 'b':2, 'c':3} ---> [('a', 1), ('b', 2), ('c', 3)]

def my_items(dict1:dict):

list_key = []

list_value = []

list_items = []

for key in dict1:

list_key.append(key)

list_value.append(dict1[key])

for tuple1 in list_key:

list_item = []

list_item.append(tuple1)

for tuple2 in list_value:

list_item.append(tuple2)

list_items.append(tuple(list_item))

break

return list_items

print(my_items({'a': 1, 'b':2, 'c':3}))

def my_items(dict1:dict):
list_key = []
list_value = []
list_item = []
list_items = []
count = 0

for key in dict1:
    list_key.append(key)
    list_value.append(dict1[key])
while count < len(list_key):
    list_item = [list_key[count],list_value[count]]
    list_items.append(tuple(list_item))
    count += 1


return list_items

print(my_items({'a': 1, 'b':2, 'c':3, 'd':4, 'e':5}))

你可能感兴趣的:(Day10-Python-作业-2019/01/05)