简体   繁体   English

如何创建数字列表作为用户输入,然后找到所提供列表的均值、中位数和众数

[英]How to create list of numbers as user input and then finding mean, median and mode of the provided list

So I want to create functions for the median, mean and mode of a list.所以我想为列表的中位数、均值和众数创建函数。 The list must be a user input.该列表必须是用户输入。 How would I go about this?我该怎么办? Thanks.谢谢。

You do not have to create functions for median, mean, mode because they are implemented already and can be called explicitly using Numpy and Scipy libraries in Python.您不必为中值、均值、模式创建函数,因为它们已经实现并且可以使用 Python 中的NumpyScipy库显式调用。 Implementing these functions would mean "reinventing the wheel" and could lead to errors and take time.实现这些功能意味着“重新发明轮子”,并可能导致错误和花费时间。 Feel free to use libraries because in most cases they are tested and safe to use.随意使用库,因为在大多数情况下它们都经过测试并且可以安全使用。 For example:例如:

import numpy as np
from scipy import stats

mylist = [0,1,2,3,3,4,5,6]
median = np.median(mylist)
mean = np.mean(mylist)
mode = int(stats.mode(mylist)[0])

To get user input you should use input().要获取用户输入,您应该使用 input()。 See https://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/io.htmlhttps://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/io.html

If this supposed to be your homework, I'll give you some hint:如果这应该是你的家庭作业,我会给你一些提示:

mean: iterate through the list, calculate the sum of elements and divide by element count意思是:遍历列表,计算元素的总和并除以元素计数

median : First, you have to sort the list elements in increasing order.中位数:首先,您必须按递增顺序对列表元素进行排序。 Then find out whether the list length is even or odd.然后找出列表长度是偶数还是奇数。 If odd, return the center element.如果是奇数,则返回中心元素。 If even, return center element and the element next to the the center and calculate their average.如果偶数,则返回中心元素和中心旁边的元素并计算它们的平均值。

mode : Create a 'helper' list first containing distinct elements of the input list. mode :创建一个“helper”列表,首先包含输入列表的不同元素。 Then, create a function that has one parameter: a number to - to be counted - how many times it is in the input list.然后,创建一个具有一个参数的函数:一个数字 - 要计算 - 它在输入列表中的次数。 Run this function in a for cycle providing the distinct list elements as input.在 for 循环中运行此函数,提供不同的列表元素作为输入。 At each iteration, save the result in a tuple: a tuple consists of (element value, element count).在每次迭代时,将结果保存在一个元组中:一个元组由(元素值,元素计数)组成。 Afterall you should have an array of tuples.毕竟你应该有一个元组数组。 When you have all this stuff, select the tuple that has the maximum "element count" and return the corresponding "element value".当你拥有所有这些东西时,选择具有最大“元素计数”的元组并返回相应的“元素值”。

Please note that these are just fast hints that can be useful in order to create your own implementation based on the right algorithm you prefer.请注意,这些只是快速提示,可用于根据您喜欢的正确算法创建您自己的实现。 This could be a good exercise to get started with algorithms and data structures, I hope you'll not skip it:) Good luck!这可能是开始学习算法和数据结构的一个很好的练习,我希望你不要跳过它:) 祝你好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM