Comparing characters in a string sequentially in Python

前端 未结 2 1580
别那么骄傲
别那么骄傲 2020-12-06 20:22

I am trying to figure out how to compare a character in a string to the next character in the string. For example, if I have a string:

s = \'vzcbotdebobeggg         


        
2条回答
  •  长情又很酷
    2020-12-06 21:15

    This is less obvious, but seems to work:

    seq = "vzcbotdebobeggglakyl"
    
    import itertools
    result = max(
        (
            list(next(sub)) + [b for a, b in sub]
            for ascending, sub in itertools.groupby(zip(seq,seq[1:]), lambda x: x[0] <= x[1])
            if ascending
        ),
        key=len
    )
    
    print ''.join(result)
    

提交回复
热议问题