简体   繁体   English

如何在不使用 .remove 的情况下从列表中删除元素

[英]How do I remove an element from a list without using .remove

I'm trying to create a function that finds the minimum value of a list and removes it, only without using .remove or min.我正在尝试创建一个函数来查找列表的最小值并将其删除,但不使用 .remove 或 min。 I have the code to find the minimum value:我有找到最小值的代码:

userlist = [1,2,3,4,5]
smallest = userlist[0]
def removeMin():
  for i in range(1, len(userlist)):
    if userlist[i] < smallest:
        smallest = userlist[i]

I've tried using .pop but clearly that does not work because smallest is a variable and not a position.我试过使用 .pop 但显然这不起作用,因为最小的是一个变量而不是一个位置。 Any help would be appreciated.任何帮助,将不胜感激。

If you are iterating through a python object, there are much better ways to iterate than using range.如果您正在遍历 Python 对象,则有比使用范围更好的迭代方法。 Any iterable can be looped through like so:任何可迭代对象都可以像这样循环:

for x in my_list:
   pass # do something

The above will step through every element set the current iteration to x .以上将逐步执行将当前迭代设置为x每个元素。 However, if you want the index as well, use the Python enumerate() built-in, which instead of giving just the item, also gives the current index, like so:但是,如果您还需要索引,请使用 Python enumerate()内置enumerate() ,它不仅提供项目,还提供当前索引,如下所示:

for index, item in enumerate(my_list):
   pass # do something

So for your function you want something like:因此,对于您的功能,您需要类似的东西:

def removeMin(my_list):
  smallestIndex = 0
  smallest = my_list[0]
  for i,val in enumerate(my_list):
    if val < smallest:
        smallest = val
        smallestIndex = i
  my_list.pop(smallestIndex)
  return my_list

edit: if it is a puzzle, the most devious way of doing it is with a list comprehension , like so:编辑:如果这是一个谜题,最狡猾的方法是使用列表理解,如下所示:

userlist.pop(userlist.index(-max([-u for u in userlist])))

This:这个:

  • creates a list comprehension, which inverts the list: [-u for u in userlist]创建一个列表理解,它反转列表: [-u for u in userlist]
  • finds the max imum of that list (which is the minimum of the normal list) max(...)找到该列表的max (这是正常列表的最小值) max(...)
  • finds in the original list the index of the first element with the value of the negative of the maximum userlist.index(-...)在原始列表中查找第一个元素的索引,其值为最大userlist.index(-...)的负值
  • and finally pops that element userlist.pop(...)最后弹出那个元素userlist.pop(...)

Voila, not a .remove or a min in sight!瞧,不是.remove或一min

Here is one straight forward approach:这是一种直接的方法:

#!/usr/bin/python

userlist = [10,2,30,4,5]
def rm_min(lis):
    minn = None
    ind = None
    for i, j in enumerate(lis):
        if minn and j < minn:
            minn = j
            ind = i
        elif not minn:
            minn = j
        else:
            pass
    return [ y for x,y in enumerate(userlist) if x != ind]

print rm_min(userlist)

Output:输出:

[10, 30, 4, 5] [10, 30, 4, 5]

Well, if your main task is merely supposed to find out and remove the smallest item in a certain list, I mean not care about the order of those elements .好吧,如果你的主要任务只是找出并删除某个列表中最小的项目,我的意思是不要关心这些元素的顺序 Maybe you can try python's heapq module.也许你可以试试 python 的heapq模块。

It provides an implementation that transforms list into a heap, in-place .它提供了一个将列表转换为堆的实现,就地 Then you can remove the smallest element of the heap in a simple and efficient way:然后你可以用一种简单有效的方式移除堆中最小的元素:

Here is a sample:这是一个示例:

import heapq

#alist could be a disordered list, it doesn't matter
alist = [10, 2, 4, 5, 8, 50]

heapq.heapify(alist)   #transform alist to heap, in-place. That means None is returned

smallest = heapq.heappop(alist)  #pop the smallest element of alist, here is 2

print smallest  #output: 2

And you can simply go on, to find out and remove the 2nd small(3rd small, 4th small, ...) element of the remaining alist , using heapq.heappop(alist) , until an IndexError raised(nothing left in alist):您可以继续使用heapq.heappop(alist)找出并删除剩余alist的第二个 small(3rd small, 4th small, ...) 元素,直到引发IndexError (alist 中没有任何剩余) :

print heapq.heappop(alist)  #output: 4

print heapq.heappop(alist)   #output: 5

print heapq.heappop(alist)   #output: 8

print heapq.heappop(alist)   #output: 10

print heapq.heappop(alist)   #output: 50

If continue... IndexError raised:如果继续... IndexError引发:

In [7]: heapq.heappop(alist)
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
/home/chiyu/<ipython-input-7-8faac314c419> in <module>()
----> 1 heapq.heappop(alist)

IndexError: index out of range

In [8]: 

You can put the heappop into a try/except block:您可以将heappop放入try/except块中:

import heapq

alist = [10, 2, 4, 5, 8, 50]

heapq.heapify(alist)

while True:
    try:
        smallest = heapq.heappop(alist)
    except IndexError:
        break

    print smallest

The output would be:输出将是:

2
4
5
8
10
50

There's one thing deserved to be mentioned again:有一点值得再次提及:

  • if you really care about the order of the elements in the given list, heapq would be unsuitable.如果您真的关心给定列表中元素的顺序,heapq 将不合适。

Because when you call heapq.heapify(alist) orders of those elements have changed:因为当你调用heapq.heapify(alist) ,这些元素的顺序发生了变化:

In [8]: alist = [10, 2, 4, 5, 8, 50]

In [9]: heapq.heapify(alist)

In [10]: alist
Out[10]: [2, 5, 4, 10, 8, 50]

Here is simple approach without any complex loops and functions这是没有任何复杂循环和函数的简单方法

arr=[1,20,5,78,30]
    count=0
    element=int(input("enter the element you want to remove:"))
    for i in range(len(arr)):
        if(arr[i]==element):
            count=count+1
    if(count>=1):
        pos=arr.index(element)
        arr1 = arr[:pos]+arr[pos+1:]
        print(arr1)
    else:
        print("element not found in array")

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

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