使用while循环从列表Python中删除负数

2024-06-28 10:10:40 发布

您现在位置:Python中文网/ 问答频道 /正文

rmNegative(L)删除list L中的负数,假定只包含数字元素。(修改L;不创建新列表。)

当我使用while循环时,我该怎么做呢?我试过一遍又一遍地编写代码,得到的只是一个永无止境的循环。。在

def rmNegatives(L):
    pos=len(L)-1
    while pos>-1:
        pos=pos
        if pos<len(L)-1:
            pos=pos
            if L[pos]>0:
                L[:]=L[:]
                pos=len(L)-2
            elif L[pos]<0:
                L[:]=[L[pos]]+L[0:]
                L[:]=L[1:]
                pos=len(L)-1

        elif pos==len(L)-1:
            pos=pos
            if L[pos]<0:
                L[0:]=L[0:pos]
                pos=len(L)-1
            elif L[pos]>0:
                L[:]=L[:]
                pos=len(L)-2

rmNegatives([-25,31,-10,23,45,-2])

Run the code here

编辑**感谢您的回复。我的代码不包含任何形式的remove或index的原因是我被限制使用它们(如果它们不包含的话会很好,但是..)


Tags: run代码pos元素列表lenifdef
3条回答

如果您绝对负担不起创建新列表的费用,并且必须使用while循环:

l = [1,2,3,-1,-2,-3,4,5]
x = 0
while x < len(l):
  if l[x] < 0:
    l.remove(l[x])
    continue
  x += 1

或者,正如abarner(较低运行时)建议的那样:

^{pr2}$

如果您绝对负担不起创建新列表的费用,但可以使用for循环:

l = [1,2,3,-1,-2,-3,4,5]
for x in xrange(len(l)):
  if x < len(l) and l[x] < 0:
    l.remove(l[x])

如果您有能力创建新列表:

l = [1,2,3,-1,-2,-3,4,5]
l = [num for num in l if num >= 0]

代码:

def rmNegatives(L):
    i = 0
    while i < len(L):
        if L[i] < 0:
            L.pop(i)
        else:
            i += 1
    return L

下面是一个带有while循环的实现。我从末尾开始,因为随着循环的迭代,列表变得越来越短,而早期的索引也因此发生了变化。在

def rmNegative(L):
    index = len(L) - 1
    while index >= 0:
        if L[index] < 0:
            del L[index]
        index = index - 1

相关问题 更多 >