python - 比较相邻值、删除相似对并比较新列表

标签 python list compare

a = [1N, 1S, 1S, 2E, 2W, 1N, 2W] 假设我有一个这样的 list 。有没有一种方法可以进行以下比较。

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)

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

最佳答案

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

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

它将产生:

[1, 2, 2, 1, 2]
[1, 1, 2]
[2]

关于python - 比较相邻值、删除相似对并比较新列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41295002/

相关文章:

Java - 对象比较算法

java - 使用compareTo(String) 按字母顺序排列数组中的字符串?

python - 多维数组索引

python - 使用多个接受参数的 fixture 进行参数化测试

java - LinkedLists 作为 HashMap 的值在修改后不包含正确的数据

Python - 列表转换

java - Custom Comparator.comparing only by field in Java 8

python - 从文件中读取行,处理它,然后删除它

实时操作系统 (RTOS) 上的 Python

python - 在Python中,有没有一种方法可以使用.format表示法将列表打印到字符串中?