从python整数列表中删除Max和Min值 [英] Remove Max and Min values from python list of integers

查看:1001
本文介绍了从python整数列表中删除Max和Min值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Python并不完全陌生,但是我对在发展自己的技能的同时学习/保持良好实践感兴趣.

I am not completely green to Python, but I am interested in learning/keeping good practices while I develop my skills.

我想从数字列表中删除较高和较低的值,我知道该怎么做,但很好奇是否有更好/更好的方法可以做到这一点.

I want to remove the high and low values from a list of numbers, which I know how to do, but am curious if there is a better/preferred way to do this.

mylist = [1, 4, 0, 3, 2]
mylist.sort() #[0, 1, 2, 3, 4]
trimmed = mylist[1:-1] #[1, 2, 3]

我得到了想要的答案,但是我得到了正确的答案吗?

I get the desired answer, but did I get the right answer appropriately?

推荐答案

如果您不想更改项目的顺序,这是另一种方法:

Here's another way to do it if you don't want to change the order of the items:

mylist = [1, 4, 0, 3, 2]
mylist.remove(max(mylist))
mylist.remove(min(mylist))

假设高/低在列表中没有任何重复项,或者如果有重复项,则可以只删除其中之一.

Assumes that the high/low don't have any duplicates in the list, or if there are, that it's OK to remove only one of them.

这将需要进行2-4次遍历列表:两个查找最大值和最小值,最多查找2个要删除的值(如果它们都恰好位于列表的末尾).您可以通过编写Python循环以一次找到最大值和最小值来减少到一个(并记住每个索引的索引,以便您可以在循环后按索引删除项目).但是,min()max()是用C实现的,因此即使使用Python代码替换它们,也可以减少通过次数,但可能会导致性能降低.

This will need to do 2-4 passes through the list: two to find the max and min values, and up to 2 to find the values to remove (if they both happen to be at the end of the list). You could reduce this to one by writing a Python loop to find the max and min in a single pass (and remember the index of each so you can delete the items by index after the loop). However, min() and max() are implemented in C, so replacing them with Python code would probably result in lower performance even if it allowed you to reduce the number of passes.

这篇关于从python整数列表中删除Max和Min值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆