Python:如何查找字符串中字母序连续子串并统计其长度?
找出字符串中按字母顺序连续排列的子串并统计长度
需求
编写Python程序,提取输入字符串中按字母顺序连续排列的子串,并统计每个子串的字符数量:
- 输入
cabin,输出abc, 3 - 输入
sightfulness,输出ghi, 3、stu, 3
当前进度与问题
已完成输入字符串转字符列表、去重、排序操作,但无法正确检查排序后列表中字母是否连续,当前代码如下:
import string a = input("Input A: ") # sorted_a is the sorted letters of the string input a sorted_a = sorted(a) print(sorted_a) # to remove the duplicate letters in sorted_a # make a temporary list to contain the filtered elements temp = [] for x in sorted_a: if x not in temp: temp.append(x) # pass the temp list to sorted_a, sorted_a list updated sorted_a = temp joined_a = "".join(sorted_a) print(sorted_a) alphabet = list(string.ascii_letters) print(alphabet) def check_list_order(sorted_a): in_order_list = [] for i in sorted_a: if any((match := substring) in i for substring in alphabet): print(match) # this should be the part # that i would compare the element # in sorted_a with the elements in alphabet # to know the order of both of them # and to put them ordered characters # to in_order_list if ord(i)+1 == ord(i)+1: in_order_list.append(i) return in_order_list print(check_list_order(sorted_a))
修正方案
原代码核心问题是连续字母的判断逻辑错误,可通过直接比较字符的ASCII码值判断连续性。同时简化去重排序步骤,以下是修正后的完整代码:
def find_consecutive_substrings(s): # 一步完成去重+按字母顺序排序 sorted_chars = sorted(set(s)) if not sorted_chars: return [] result = [] current_sub = [sorted_chars[0]] for char in sorted_chars[1:]: # 判断当前字符是否是前一个字符的下一个字母 if ord(char) == ord(current_sub[-1]) + 1: current_sub.append(char) else: # 仅收集长度≥2的连续子串(匹配示例需求) if len(current_sub) >= 2: result.append(("".join(current_sub), len(current_sub))) current_sub = [char] # 处理循环结束后剩余的连续子串 if len(current_sub) >= 2: result.append(("".join(current_sub), len(current_sub))) return result # 执行逻辑 input_str = input("Input A: ") substrings = find_consecutive_substrings(input_str) for sub, length in substrings: print(f"{sub}, {length}")
关键逻辑说明
- 去重排序优化:用
sorted(set(s))替代原循环去重,代码更简洁高效 - 连续性判断:通过
ord(char) == ord(current_sub[-1]) + 1直接校验字符是否连续 - 子串收集:用临时列表跟踪当前连续序列,遇到断点时保存有效子串,最后处理剩余序列
- 输出适配:按示例格式输出每个子串和对应长度
内容的提问来源于stack exchange,提问作者Kite
相关产品推荐
相关产品推荐

