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

时间:2014-10-14 03:42:20

标签: python

我尝试创建一个找到列表最小值的函数并将其删除,但不使用.remove或min。我有代码来找到最小值:

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]

我尝试过使用.pop,但显然不起作用,因为minimal是变量而不是位置。任何帮助将不胜感激。

4 个答案:

答案 0 :(得分:1)

如果您正在迭代python对象,那么迭代比使用范围有更好的方法。任何可迭代都可以像这样循环:

for x in my_list:
   pass # do something

上面将逐步完成将当前迭代设置为x的每个元素。但是,如果您还想要索引,请使用内置的Python enumerate(),而不是只提供项目,也会提供当前索引,如下所示:

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

因此,对于您的功能,您需要以下内容:

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

编辑:如果它是一个谜题,那么最狡猾的做法是使用list comprehension,如下所示:

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

此:

  • 创建一个列表推导,它反转列表:[-u for u in userlist]
  • 找到该列表的max imum(这是正常列表中的最小值)max(...)
  • 在原始列表中查找第一个元素的索引,其值为最大值userlist.index(-...)
  • 最后弹出元素userlist.pop(...)

Voila,而不是.removemin

答案 1 :(得分:0)

这是一种直接的方法:

#!/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)

输出:

[10,30,4,5]

答案 2 :(得分:0)

好吧,如果你的主要任务只是找出并删除某个列表中的最小项目,我的意思是不关心这些元素的顺序。也许你可以试试python的heapq模块。

它提供了一个实现,可以将列表转换为堆,就地。然后,您可以以简单有效的方式删除堆中最小的元素:

以下是一个示例:

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

你可以继续使用alist查找并删除剩余heapq.heappop(alist)的第二个小(第3小,第4小......)元素,直到{{ 1}}提出(没有留在alist中):

IndexError

如果继续...... 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 被提出:

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]: 放入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

有一件事值得再次提及:

  • 如果您真的关心给定列表中元素的顺序, heapq不合适。

因为当你致电2 4 5 8 10 50 时,这些元素的订单发生了变化:

heapq.heapify(alist)

答案 3 :(得分:0)

这是一种简单的方法,没有任何复杂的循环和功能

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")
相关问题