递减要在for循环中递增的变量 [英] Decrement the Variable I'm Incrementing in for loop

查看:130
本文介绍了递减要在for循环中递增的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有点像Python的新手,我环顾了一下,但没有找到令人满意的答案.我在做一些练习题,我想做一个摆脱列表中重复值的方法.到目前为止,这是我的代码:

kind of a newbie to Python and I've looked around a bit but haven't found a satisfying answer to my question. I'm doing some practice problems and I want to make a method that gets rid of duplicate values in a list. So far, this is my code:

def noDouble(nums):
  for x in xrange(len(nums) - 2):
      if nums[x] == nums[x + 1]:
          nums.pop(x)
          x -= 1
  return nums

我想发生的是,如果有重复项,请弹出其中一个重复项,然后再次移回(这样,如果有3个相同编号的实例,它将消除所有通过倒带").

What I want to happen is that if there's a duplicate, pop off one of the duplicates and then move back again (so that if there are, say, 3 instances of the same number, it'll get rid of al of them by 'rewinding').

我正在寻找一个解释,为什么我的代码无法正常工作以及解释性的解决方案,我非常感谢您提供的所有帮助.谢谢.

I'm looking for an explanation for why my code doesn't work as well as an explained solution and I'd really appreciate any and all help. Thanks.

推荐答案

因为for不计算数字;它遍历一个序列.每次循环主体执行时,x都会设置为xrange生成的下一个值. for语句根本不在乎循环结束时x是什么.

Because for doesn't count numbers; it iterates over a sequence. Every time the body of the loop executes, x is set to the next value produced by the xrange. The for statement couldn't care less what x is at the end of the loop.

无论如何,您实际上不应该在循环中修改列表.这样做的更简单方法是建立一个新列表:

You really shouldn't modify a list within a loop over it, anyway. The easier way to do this is to build a new list:

def remove_doubles(old):
    new = []
    for item in old:
        if new and item == new[-1]:
            continue
        new.append(item)
    return new

当然,真正删除重复项的简单方法是list(set(foo)).但这将删除所有重复项,而不仅仅是相邻重复项,并且可能还会破坏项目顺序.

Of course, the really easy way to remove duplicates is list(set(foo)). But that will remove all duplicates, not just adjacent ones, and probably destroy the item order too.

这篇关于递减要在for循环中递增的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆