从 python 整数列表中删除最大值和最小值
我对 Python 并不完全陌生,但我有兴趣在发展技能的同时学习/保持良好的实践。
我想从数字列表中删除高值和低值,我知道该怎么做,但我很好奇是否有更好/首选的方法来做到这一点。
mylist = [1, 4, 0, 3, 2]
mylist.sort() #[0, 1, 2, 3, 4]
trimmed = mylist[1:-1] #[1, 2, 3]
我得到了想要的答案,但是我得到了正确的答案吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您不想更改项目的顺序,还有另一种方法:
假设列表中的最高/最低值没有任何重复项,或者如果有,则可以仅删除其中一个。
这需要对列表进行 2-4 次遍历:两次查找最大值和最小值,最多 2 次查找要删除的值(如果它们都恰好位于列表末尾)。您可以通过编写一个 Python 循环来在一次传递中查找最大值和最小值,从而将其减少到 1(并记住每个循环的索引,以便您可以在循环后按索引删除项目)。但是,
min()
和max()
是用 C 实现的,因此用 Python 代码替换它们可能会导致性能降低,即使它允许您减少通过。Here's another way to do it if you don't want to change the order of the items:
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.
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()
andmax()
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.我想出这个是因为我试图修改的列表中有重复项,所以我没有多次运行 mylist.remove(min(mylist)) 因为它一次只删除一个值,而是在一行中修改了它
I came up with this because I had duplicates in the list I was trying to modify, so instead of running mylist.remove(min(mylist)) multiple times because it only removes one value at a time I modified it in one line
我必须删除最大元素并将列表存储在变量中,并且与最小元素相同。通过使用删除函数,如果我将其存储在变量中,则不会给出任何结果
输出。所以要存储它
I had to remove max element and store the list in a variable and same with min element. By using remove function if I stored it in variable it gives none as
output. So to store it
您只需 2 次即可删除最小和最大元素。也不需要排序
[这假设列表中的最小值和最大值没有重复项]
You can remove min and max elements in just 2 passes. No sort needed either
[This assumes min and max values have no duplicates in the list]