【问题标题】:Comparing adjacent values, deleting like pairs and comparing new list比较相邻值,删除相似对并比较新列表
【发布时间】:2016-12-23 04:01:19
【问题描述】:

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)

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

【问题讨论】:

  • 尝试编写代码(以及您遇到的问题)以便我们为您提供帮助。
  • 小心!您在 dirReduc 函数末尾缺少 return(它应该类似于“返回临时列表”)。没有函数返回None。还需要在最后一行关闭)

标签: python list compare


【解决方案1】:

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

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]

【讨论】:

    猜你喜欢
    • 2021-12-07
    • 2015-09-09
    • 2020-08-25
    • 2020-07-16
    • 1970-01-01
    • 2020-01-18
    • 2012-12-26
    • 2020-06-17
    • 1970-01-01
    相关资源
    最近更新 更多