首页 > 解决方案 > 在从 python 中获得用户的姓名列表后,按字母顺序显示名字和按字母顺序显示姓氏

问题描述

设计一个程序,询问用户一系列的名字(没有特定的顺序)。输入最后一个人的姓名后,程序应显示按字母顺序排在第一位的姓名和按字母顺序排在最后一位的姓名。例如,如果用户输入名字 Kristin、Joel、Adam、Beth、Zeb 和 Chris,程序将显示 Adam 和 Zeb。

注意:必须使用条件控制循环。用户将输入一个标记值 DONE 以指示没有更多名称要输入。

我们真的没有在课堂上讨论过这个,我试着在网上查一下,看看我是否能理解任何东西,但大多数人都在用 java 或 C++ 询问它。

我的代码:

# Prompt user to enter names
names = input("Enter the names: ")
# breakdown the names into a list
words = names.split()
# sort the names
words.sort()
# display the sorted names
print("The sorted names are:")
for word in words:
    print(word)

标签: python

解决方案


这是一个可以解决您的问题的代码:

print("Keep entering names by typing space bar after every name. Once done, press Enter")
final_list = list(map(str, input().rstrip().split()))
final_list.sort()
print("The first name is {}. The last name is {}".format(final_list[0],final_list[-1]))

推荐阅读