以下是一个示例代码,用于按照字母顺序对给定的字符串列表进行排序:
# 定义一个字符串列表
strings = ["apple", "banana", "orange", "grape", "cherry"]
# 使用sorted函数对字符串列表进行排序,并存储到新的变量中
sorted_strings = sorted(strings)
# 打印排序后的字符串列表
for string in sorted_strings:
print(string)
输出:
apple
banana
cherry
grape
orange
在上述代码中,我们使用了sorted()
函数对字符串列表进行排序。sorted()
函数可以对可迭代对象进行排序,并返回一个新的已排序的列表。在这个示例中,我们将字符串列表strings
传递给sorted()
函数,并将返回的已排序列表存储在sorted_strings
变量中。然后,我们使用for
循环遍历sorted_strings
列表,并打印每个字符串。这样就实现了按字母顺序对字符串列表进行排序的需求。
上一篇:按照字母顺序排列单词
下一篇:按照字母顺序排序