python - 如何检查输入的字符串列表是否按字母顺序排列?
问题描述
我有一个程序,它从用户输入中获取一系列字符串,如果输入的字符串按字母顺序排列,则应打印“是”,否则应打印“否”。该程序以用户输入一个空输入而结束。当我指定它应该具有的输入数量时,我可以这样做,例如 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
有没有一种简单的方法可以在不偏离上述预期结构太远的情况下实现这一目标?
解决方案
我对您的代码进行了一些更改。不需要两个输入和一个主列表。代码如下。假设
- 假设列表中的项目由单个空格分隔
- 大写字符和小写字符之间的区别并不重要。如果这不正确并且 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:
推荐阅读
- javascript - 递归 setTimeout 中的递归 setTimeout
- java - 在类文件中引用多个枚举之一
- java - Soap UI 使用肥皂信封中的什么来创建 XMLDsig 签名?
- android - Firebase 身份验证单元测试错误 No Firebase App
- javascript - 在 jQuery 中选择根域(主页)
- node.js - ConnectionError: 无法连接到 localhost:3306 - 在 node.js 中的流被破坏后无法调用 write 我在运行时遇到错误
- c# - 如何在 C# 中关闭 .chm 文件?
- javascript - 删除事件监听器看不到类函数
- tensorflow - 设置 Keras 模型获得嵌入文本、LSTM、自动编码器的正确输出张量形状
- python - 我无法在 python 中发送附件