【问题标题】:How can find the substrings that are in alphabetical order within a sorted string list? Python如何在已排序的字符串列表中找到按字母顺序排列的子字符串? Python
【发布时间】:2022-11-10 22:41:00
【问题描述】:

我应该创建一个程序,该程序将查找给定输入中按字母顺序排列的字符,并查找该特定子字符串或子字符串中有多少个字符。

例如 输入:机舱 输出:abc,3

输入:视力 输出: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))


【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    你可以尝试这样的事情:

    string = input("Input string: ")
    chars = sorted(set(string.strip().casefold()))
    parts, part = [], ""
    for a, b in zip(chars, chars[1:] + ["-"]):
        part += a
        if ord(a) + 1 != ord(b):
            if len(part) > 1:
                parts.append(part)
            part = ""
    
    print(parts)
    

    输入字符串"sightfulness" 的结果parts 将是

    ['efghi', 'stu']
    

    所以我不太确定为什么你的输出不同:有没有你没有提到的要求?

    如果- 可能是字符串的一部分,则将... + ["-"] 替换为更合适的内容。如果你想排除任何不在字母表中的字符,那么你可以这样做:

    from string import ascii_lowercase as alphabet
    
    string = input("Input string: ")
    chars = sorted(set(string.strip().casefold()).intersection(alphabet))
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-14
      • 2015-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多