python 中的字符串字符之间的不等式

Inequality between string characters in python

我是 Whosebug 的新手,如果我有任何格式错误,请原谅我。

我正在尝试提取最大的子字符串(变量名称为 'longest_string'),它遵循字母顺序(即 a、b、x、y、z 有效,但 a、c、b 无效) 来自字符串(变量名 's')。

我试图做的是创建一个循环,遍历“s”中的每个字符,并分配字符串 s[ 的第一个字符=39=] 到变量 'current_value' 并将其添加到名为 'strings' 的列表中。然后,我比较后面的字符,看那个字符是否大于或等于current_value。如果是,那么我将它添加到 'strings',如果不是,我将初始的 'strings' 列表分配给'longest_string' 列出并刷新变量 'current_value' 和 'strings'。每次后续字符小于'current_value'时,将当前'strings'的长度与'longest_string',最长的一个被分配为'longest_string'。

我的理解是Python假定第26个英文字符中的第一个字母是最小的(即'a'>'z'将return假) .但是,当我 运行 下面的代码时:

s = 'zcbobobegghakl'
longest_string = None
current_value = None
strings = []

for i in s:
    if not current_value:
        current_value = i
        strings.append(i)
        continue

    if i >= current_value:
        strings.append(i)

    if i < current_value:
        if not longest_string or len(longest_string) < len(strings):
            longest_string = strings
        current_value = i
        strings = []
        
print(longest_string)

我得到的是这个输出:

['o', 'b', 'o', 'b', 'e', 'g', 'g', 'h']

为什么字符 'b' 被分配到与 'o' 相同的字符串中,而显然 'b' > 'o' 将 return False 因此把第二个IF语句设为False,那岂不是一开始就不执行第二个IF语句了?

尝试将其添加到循环的开头。也许这会让您有所了解?

...
for i in s:
    print(i, current_value, strings)
    if not current_value:
...

Why is it that the character 'b' got assigned into the same string as 'o'

current_value只会减少,遇到第一个b后继续积累,直到找到a