gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:51:04 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com