如何从列表中删除小于前一个数字的目标值的值

时间:2016-05-30 23:09:09

标签: python list

鉴于已增加数字的排序列表,我正在尝试创建一个新列表,该列表仅保留至少比前一个数字大3的值。我尝试了一些条件语句,但未能获得正确的格式。例如,来自

a = [3,4,8,12,14,16]

我们会得到

new_a = [3,8,12,16]

只有14个会退出,因为距离12小于3,但是保持16,因为它从12开始大于3.还有4个会退出。任何帮助将不胜感激!

3 个答案:

答案 0 :(得分:5)

这应该做:

<!--<authentication mode="Windows"/>-->
<authentication mode="Forms">
  <forms name="AuthCookie" path="/" loginUrl="login.aspx" protection="All" timeout="2000">
    <credentials passwordFormat="Clear" />
  </forms>
</authentication>
<authorization>
  <!--<allow roles="***" />
  <deny users="*" />-->
  <deny users="?" />
  <allow users="*" />
</authorization>

答案 1 :(得分:0)

a = [3,4,8,12,14,16]
b = a[:1]
last_num = b[0]
for num in a:
    if last_num is not None and last_num + 3 <= num:
        b.append(num)
        last_num = num

print(b)

答案 2 :(得分:0)

可能有点矫枉过正,但如果你最终做了很多计算(以及在列表中添加新数字),你可以尝试继承list

class Newlist(list):
    def __init__(self, *args):
        super(Newlist, self).__init__(*args)
        if len(self) > 0:
            i = 1
            while i<len(self):
                if self.__getitem__(i) < 3+self.__getitem__(i-1):
                    self.remove(self.__getitem__(i))
                i += 1

    def append(self, item):
        if len(self) == 0:
            super(Newlist, self).append(item)
        elif item >= self.__getitem__(-1) + 3:
            super(Newlist, self).append(item)
        else: return

因此,您可以使用

初始化列表
a = Newlist([3, 4, 8, 12, 14, 16])

会自动缩短为[3, 8, 12, 16]

此外,append被覆盖,仅允许遵循您的规则的新值。示例:a.append(20)会将20添加到a的末尾,但a.append(17)将不执行任何操作。