list.remove(x):x不在列表中,当试图找到中位数时(list.remove(x): x not in list, when trying to find median)

编程入门 行业动态 更新时间:2024-10-11 09:23:34
list.remove(x):x不在列表中,当试图找到中位数时(list.remove(x): x not in list, when trying to find median)

谁能告诉我为什么这不起作用? 我得到错误说: ValueError: list.remove(x): x not in list 。

但是,如果我尝试print max ; 它打印9,如果我print min ; 它打印1。

list = [3,1,4,9,5,7] max = list[0] min = list[0] list = list[:] while len(list)> 2: for i in list: if(i > max): max = i elif(i < min): min = i list.remove(min) list.remove(max) print list

我需要从列表中删除max和min元素,直到只有2个元素才能获得列表的中位数。

Could anyone tell me why this isn't working? I got error saying: ValueError: list.remove(x): x not in list.

But if I try print max; it prints 9, and also if I print min; it prints 1.

list = [3,1,4,9,5,7] max = list[0] min = list[0] list = list[:] while len(list)> 2: for i in list: if(i > max): max = i elif(i < min): min = i list.remove(min) list.remove(max) print list

I need to remove max and min element from list, until there are only 2 elements in order to get the median of the list.

最满意答案

您的问题是您只在while循环之外初始化一次最小和最大变量。

如果在循环内部初始化,则代码将起作用。

这段代码有效。 请注意,我将变量名称更改为不是Python内置函数。 你不应该使用“影子”内置的名字; 例如, list是内置类型,因此不应将list用作变量名。

lst = [3,1,4,9,5,7] lst = lst[:] while len(lst)> 2: max_val = lst[0] min_val = lst[0] for i in lst: if(i > max_val): max_val = i elif(i < min_val): min_val = i lst.remove(min_val) lst.remove(max_val) print lst

请注意,您的代码非常低效且速度慢。 您可以使用内置函数max()和min()来加快速度,但算法仍然效率低下。

最好的方法是对列表进行排序,然后从列表中间选择单个值(对于奇数长度列表)或平均中间两个值(对于偶数长度列表)。 或者只是使用Python提供的一个内置函数。

如何找到中位数

Your problem is that you only initialize the min and max variables once, outside the while loop.

Your code will work if you initialize inside the loop.

This code works. Note that I changed the variable names to not be Python built-ins. You shouldn't use names that "shadow" built-ins; for example, list is a built-in type, so you shouldn't use list as a variable name.

lst = [3,1,4,9,5,7] lst = lst[:] while len(lst)> 2: max_val = lst[0] min_val = lst[0] for i in lst: if(i > max_val): max_val = i elif(i < min_val): min_val = i lst.remove(min_val) lst.remove(max_val) print lst

Note that your code is tremendously inefficient and slow. You could speed it up a bit by using the built-in functions max() and min() but the algorithm is still inefficient.

The best thing is to just sort the list, and then pick the single value from the middle of the list (for an odd-length list) or average the middle two values (for an even-length list). Or simply use one of the built-in functions that Python provides.

How to find Median

更多推荐

本文发布于:2023-08-01 07:00:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1354194.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中位数   列表中   remove   list   find

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!