简体   繁体   English

以连续方式计算列表中相同的连续元素

[英]Counting identical consecutive elements in a list in a continuous manner

Given a list x of number entries, I aim to find the number of identical consecutive entries, where the identical consecutive entries are taken out once counted.给定一个x的数量条目列表,我的目标是找到相同的连续条目的数量,其中相同的连续条目在计数后被取出。 For example, if x = [4, 3, 1, 1, 3, 2, 4] , the returned solution should be 4 :例如,如果x = [4, 3, 1, 1, 3, 2, 4] ,则返回的解应该是4

[4, 3, (1, 1), 3, 2, 4] => (two consecutive entries of 1s are counted: 2)
[4, (3, 3), 2, 4] => (two consecutive entries of 3s are counted: 4)
[4, 2, 4] => (no more consecutive entries: final solution is 4)

I can use the for loop to count the identical consecutive entries, but efficiently removing the elements and running them continuously until there are no more identical consecutive entries is where I find things tricky.我可以使用for循环来计算相同的连续条目,但有效地删除元素并连续运行它们直到没有更多相同的连续条目是我发现事情棘手的地方。

solution = 0

for i in range(len(x)-1):
    if x[i] == x[i+1]:
        solution += 2
        if x[i-1] == x[i+2]:
             solution += 2
...

where I know these recursive approaches are only applicable to particular lists.我知道这些递归方法仅适用于特定列表。 Using itertools only 'collapses' the length of the list, which is not something I'm looking for.使用itertools只会“折叠”列表的长度,这不是我想要的。 Is there an optimal way to calculate the number of identical consecutive entries?是否有一种最佳方法来计算相同的连续条目的数量?

Use a stack.使用堆栈。 If top (last) elememt of stack is same as current element n in x, anihilate it (pop()).如果堆栈的顶部(最后)元素与 x 中的当前元素 n 相同,则将其删除(pop())。 Otherwise, push n into stack.否则,将 n 压入堆栈。 ans is not really needed - when the loop ends, len(x)-len(stack) is the result. ans并不是真正需要的 - 当循环结束时, len(x)-len(stack)就是结果。

x = [4, 3, 1, 1, 3, 2, 4]
stack,ans=[],0
for n in x:
    if not stack or stack[-1]!=n:
        stack.append(n)
    else:
        ans+=2
        stack.pop()
print(ans)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM