如何使用python函数求平均数,中位数
""" 1.计算出这个列表的平均值 2.返回两个列表,将这个列表中大于平均数的 放在一个列表 小于平均数的放在列表 (2, 3 , 7 ,9 , 12)--> 返回的结果是【2,3,7】 ,【9,12】 3.找到这个列表中的中位数 4.写一个函数,传递的参数是【22.5】,返回值【5,22】 5.写一个函数,传递的参数是【2.5.3】,把最大的值放在第一位 """ list2 = [2, 3, 7, 9, 12] # 第一题 def avg_func(list1): a = 0 i = 0 while i < len(list1): a += (list1[i]) i += 1 sum_avg = a / len(list1) return sum_avg sum_avg2 = avg_func(list2) print(sum_avg2) print("==============================================") # 第二题 list_x = [] list_y = [] def avg_func2(): j = 0 while j < len(list2): if int(list2[j]) < sum_avg2: list_x.append(list2[j]) else: list_y.append(list2[j]) j += 1 avg_func2() print(list_x, list_y) print("==============================================") # 第三题 list_median = [2, 3, 7, 9, 12, 45] def median(list_1): k = 0 if len(list_1) % 2 == 0: k = (list_1[len(list_1) // 2] + list_1[len(list_1) // 2 - 1]) / 2 print(k) if len(list_1) % 2 != 0: k = list_1[len(list_1) // 2] print(k) median(list_median) print("==============================================") # 第四题 list_compare = [25, 5] def compare(tony): n = 0 for n in range(len(tony)): j = 0 for j in range(len(tony) - 1 - n): if tony[j] > tony[j + 1]: list_container = [] list_container = tony[j] tony[j] = tony[j + 1] tony[j + 1] = list_container print(tony) compare(list_compare) print("==============================================") # # 第五题 list_compare = [2, 5, 3] def compare(tony): n = 0 for n in range(len(tony)): j = 0 for j in range(len(tony) - 1 - n): if tony[j] < tony[j + 1]: list_container = [] list_container = tony[j] tony[j] = tony[j + 1] tony[j + 1] = list_container print(tony) compare(list_compare)
注释属实不想写