python - 在从 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)
解决方案
这是一个可以解决您的问题的代码:
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]))
推荐阅读
- javascript - 有没有办法在 datalist 元素中呈现可点击的选项标签?
- r - 在R中将数据框拆分为一定数量的组
- bash - 在bash中转换日期格式
- html - 如何将背景图像(png 图像格式)添加到具有伪元素 ::before 的 div
- amazon-web-services - AWS 系统管理器 + CodeDeploy + Lightsail
- java - 使用模式匹配 instanceof 和 switch 表达式的 Gradle Java 编译错误
- drupal - 将一个类型的内容引用到另一个常量类型
- unit-testing - EFCore xunit 断言 .Include 是否被调用
- python - “未找到 Python,但可以从 Microsoft 商店安装”
- linux - 如何使用sed将双引号保留在双引号中