a = [1n,1s,1s,2e,2W,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)
测试案例会产生正确的值,但是我需要运行循环,直到只能得到两个。那就是我卡住
如果您可以理解问题,则只需要一段时间就可以根据需要进行迭代。
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]