简体   繁体   English

删除列表中的最小值 python 问题

[英]Remove the smallest value in a list python question

The question asks to build a function that will return the list of numbers except the first encountered minimum number in that list.该问题要求构建一个 function ,它将返回除该列表中第一个遇到的最小数字之外的数字列表。 And if an empty list is provided than return an empty list.如果提供了一个空列表,则返回一个空列表。 For example: [1, 2, 3, 1, 1] -> [2, 3, 1, 1] My code though is returning [2, 3] only even though the two ones in the back of the list were not encountered before the first one and thus should not be returned.例如: [1, 2, 3, 1, 1] -> [2, 3, 1, 1] 我的代码只返回 [2, 3] 即使没有遇到列表后面的两个在第一个之前,因此不应返回。 My code:我的代码:

def remove_smallest(numbers):
    list1 = []
    if len(numbers) == 0:
        return numbers
    for number in numbers[:len(numbers)]:
        if numbers.index(number) != numbers[numbers.index(min(numbers))]:
            list1.append(number)
    return list1

Expected: [1, 2, 3, 1, 1] -> [2, 3, 1, 1] Output: [2, 3]预期:[1、2、3、1、1] -> [2、3、1、1] Output:[2、3]

With the for loop and the if statement, you have filtered all the numbers that are not the minimum number.使用 for 循环和 if 语句,您已经过滤了所有不是最小数字的数字。

def remove_smallest(numbers):
    if len(numbers) == 0:
        return numbers
    for number in numbers[:len(numbers)]:
        if(number == min(numbers)):
            numbers.remove(number)
            break
    return numbers  

This would be a better code.这将是一个更好的代码。 There is a break statement to exit the loop when the if condition is satisfied and the pointer goes into the if block.当 if 条件满足并且指针进入 if 块时,有一个 break 语句退出循环。

There can be more efficient ways to solve this too.也可以有更有效的方法来解决这个问题。

The solution is pretty simple.解决方案非常简单。 Use this:用这个:

def remove_smallest(numbers):
    smallest = min(numbers)
    for number in numbers:
        if number == smallest:
            numbers.remove(number)
    return numbers

Hope this is what you needed希望这是你需要的

Take a copy of the input list then:然后复制输入列表:

def remove_smallest(numbers):
    if numbers is None or len(numbers) == 0:
        return []
    copy = numbers.copy()
    copy.remove(min(numbers))
    return copy

print(remove_smallest([1,0,0,1]))

output: output:

[1, 0, 1]

Alternative:选择:

def remove_smallest(numbers):
    if numbers is None or len(numbers) == 0:
        return []
    i = numbers.index(min(numbers))
    return numbers[:i] + numbers[i+1:]

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

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