比较相邻值,删除相似的对并比较新列表

时间:2016-12-23 04:01:19

标签: python list compare

a = [1N,1S,1S,2E,2W,1N,2W] 说我有这样的清单。有没有办法比较它将执行以下操作。

Pseudo code: Iterate over list [1N, 1S, 1S, 2E, 2W, 1N, 2W], 1==1, delete those values. Iterate over
new list [1S, 2E, 2W, 1N, 2W], 1!=2, move on, 2==2 delete those values. Iterate
over new list [1S, 1N, 2W], 1==1, delete those values. Answer = 2W

到目前为止我所拥有的。

def dirReduc(arr):
    templist = []
    for i in range(1, len(arr)):
        a = arr[i - 1]
        b = arr[i]
        if a == b:
            templist = (arr[b:])
    (templist)
a = [1, 1, 1, 2, 2, 1, 2]
print(dirReduc(a)

测试用例产生正确的值,但我需要运行循环直到我只得到两个。那就是我被困的地方

1 个答案:

答案 0 :(得分:1)

如果你能理解这个问题,你只需要一段时间就可以根据需要进行迭代。

class Parent {
    private(set) var name = "Dad"
}

class Child: Parent {
    override var name: String { return "Son" }
}

它会产生:

a = [1, 1, 1, 2, 2, 1, 2]
finished = False
while not finished:    # Iterate until finished = True
    finished = True    # That only happens when no repeated elements are found
    for i in range(len(a)-1):
        if a[i] == a[i+1]:
            a.pop(i)   # When removing the element i from a,
            a.pop(i)   # now the i + 1 is in the place of i
            print(a)
            finished = False
            break