首页 > 解决方案 > 如何检查输入的字符串列表是否按字母顺序排列?

问题描述

我有一个程序,它从用户输入中获取一系列字符串,如果输入的字符串按字母顺序排列,则应打印“是”,否则应打印“否”。该程序以用户输入一个空输入而结束。当我指定它应该具有的输入数量时,我可以这样做,例如 2:

finished = False
while not finished:
    print("Please enter a string: ")
    s = input()
    x = input()
    if len(s) != 0: 
        if s < x:
            print("Yes")
        else:
            print("No")  
    else:
        finished = True

但是,当可以输入的字符串数量不定时,我似乎无法让我的代码工作。我目前的工作方法是将所有字符串附加到一个列表并在那里执行检查,但我不确定如何编写 if 语句来检查这个:

lst = []
i = range(len(lst))

finished = False
while not finished:
    print("Please enter a string: ")
    s = input()
    lst.append(s)
    if len(s) != 0:
        if lst[i:] < lst[i: - 1]:
            print("Yes")
        else:
            print("No")
    else:
        finished = True

有没有一种简单的方法可以在不偏离上述预期结构太远的情况下实现这一目标?

标签: pythonstringlistalphabetical

解决方案


我对您的代码进行了一些更改。不需要两个输入和一个主列表。代码如下。假设

  • 假设列表中的项目由单个空格分隔
  • 大写字符和小写字符之间的区别并不重要。如果这不正确并且 ASCII 排序很重要,则从第三行中删除“.lower()”。
while True:
    print("Please enter a string: ")
    s = input().lower() ## To avoid confusion between sorting ABb Abb and like strings
    if not s: ## If nothing is entered break out of loop
        break
    SplitString = s.split(" ") ##Get elements separated by "single" space into list
    SortedString = " ".join(sorted(SplitString)) ##Sort the list and then join into string
    if s == SortedString: ##If the sorted and joined string is same as original then the string was already sorted when entered
        print("Yes")
    else: ## Else it was not sorted when entered
        print("No")

输出如下

Please enter a string: 
AAA AAB ABA ABC
Yes
Please enter a string: 
AAA AAB ABC ABA
No
Please enter a string: 
aaa aab aba abc
Yes
Please enter a string: 
aaa aab abc aba
No
Please enter a string: 


推荐阅读