简体   繁体   English

python中的条件循环

[英]Conditional loop in python

list=['a','a','x','c','e','e','f','f','f']

i=0
count = 0

while count < len(list)-2:
    if list[i] == list[i+1]:
        if list [i+1] != list [i+2]:
            print list[i]
            i+=1
            count +=1
        else:print "no"
    else:   
        i +=1
        count += 1

I'm getting: 我越来越:

    else:print "no"
   ^
 IndentationError: unexpected indent

I'm trying to only print the elts that match the following element, but not the element following that. 我试图只打印匹配以下元素的elts,但不打印后面的元素。 I'm new to Python, and I'm not sure why this isn't working. 我是Python的新手,我不确定为什么这不起作用。

Here is the fixed-up code (added a count += 1 after the else-clause to make sure it terminates): 这是修复后的代码(在else子句之后添加了一个count += 1以确保它终止):

list=['a','a','x','c','e','e','f','f','f']

i=0
count = 0

while count < len(list)-2:
    if list[i] == list[i+1]:
        if list [i+1] != list [i+2]:
            print list[i]
            i+=1
            count +=1
        else:
            print "no"
            count += 1
    else:   
        i +=1
        count += 1

A more advanced solution using itertools is more compact and easier to get right: 使用itertools的更高级解决方案更紧凑,更容易正确:

from itertools import groupby

data = ['a','a','x','c','e','e','f','f','f']
for k, g in groupby(data):
    if len(list(g)) > 1:
        print k

The code works for me without error (although you get stuck in a loop). 代码对我没有错误(虽然你陷入了循环)。 Make sure you are not mixing tabs and spaces. 确保没有混合标签和空格。

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

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