Python程序检查所有字符串元素的字符是否按词法顺序排列
给定一个包含字符串元素的列表,任务是编写一个Python程序,如果所有列表元素都已排序,则返回 True。这里的注意点是要记住,我们将字符列表元素的字符串与同一列表元素的其他字符进行比较,而不是将字符串元素相互比较。
例子:
Input : test_list = [“dent”, “flop”, “most”, “cent”]
Output : True
Explanation : All characters are sorted.
Input : test_list = [“dent”, “flop”, “mist”, “cent”]
Output : False
Explanation : m > i in mist, hence unordered. So, False is returned.
方法 1:使用循环和sorted()
在这里,我们对每个字符串进行迭代并测试是否所有字符串都使用 sorted() 进行排序,如果任何字符串未排序/排序,则结果被标记为关闭。
例子:
Python3
# initializing list
test_list = ["dent", "flop", "most", "cent"]
# printing original list
print("The original list is : " + str(test_list))
res = True
for ele in test_list:
# check for ordered string
if ele != ''.join(sorted(ele)):
res = False
break
# printing result
print("Are all strings ordered ? : " + str(res))
Python3
# initializing list
test_list = ["dent", "flop", "most", "cent"]
# printing original list
print("The original list is : " + str(test_list))
# using all() to check all elements to be sorted
res = all(ele == ''.join(sorted(ele)) for ele in test_list)
# printing result
print("Are all strings ordered ? : " + str(res))
输出:
The original list is : [‘dent’, ‘flop’, ‘most’, ‘cent’]
Are all strings ordered ? : True
方法 2:使用all()和sorted()
在这种情况下,避免了循环并使用 all() 检查所有要排序的字符串,如果所有元素在特定条件下都返回 true,则返回 True。
例子:
蟒蛇3
# initializing list
test_list = ["dent", "flop", "most", "cent"]
# printing original list
print("The original list is : " + str(test_list))
# using all() to check all elements to be sorted
res = all(ele == ''.join(sorted(ele)) for ele in test_list)
# printing result
print("Are all strings ordered ? : " + str(res))
输出:
The original list is : [‘dent’, ‘flop’, ‘most’, ‘cent’]
Are all strings ordered ? : True