简体   繁体   English

如何在 CodeHS 8.4.12 中仅打印姓氏:图书管理员,第 2 部分?

[英]How do I print only the last names on CodeHS 8.4.12: Librarian, Part 2?

This is what I'm supposed to do: In the Librarian exercise, you asked the user for five last names, and you then printed a list of those names in sorted order.这是我应该做的:在图书管理员练习中,您要求用户提供五个姓氏,然后按排序顺序打印这些名字的列表。

In this exercise, you will ask the user for five full names.在本练习中,您将要求用户提供五个全名。 You should still print a list of last names in sorted order.您仍然应该按排序顺序打印姓氏列表。

Each time you retrieve a name from the user, you should use the split method and the right index to extract just the last name.每次从用户那里检索姓名时,您应该使用 split 方法和正确的索引来仅提取姓氏。 You can then add the last name to the list of last names that you will ultimately sort and print.然后,您可以将姓氏添加到您最终将排序和打印的姓氏列表中。

Here's what an example run of your program might look like:以下是您的程序的示例运行情况:

Name: Maya Angelou
Name: Chimamanda Ngozi Adichie
Name: Tobias Wolff
Name: Sherman Alexie
Name: Aziz Ansari
['Adichie', 'Alexie', 'Angelou', 'Ansari', 'Wolff']

This is my code right now:这是我现在的代码:

name_1 = input("Name: ")
name_1.split()
name_2 = input("Name: ")
name_2.split()
name_3 = input("Name: ")
name_3.split()
name_4 = input("Name: ")
name_4.split()
name_5 = input("Name: ")
name_5.split()
my_list = [name_1[-1], name_2[-1], name_3[-1], name_4[-1], name_5[-1]]
my_list.sort()
print my_list

My code right now prints only the last letter, not the last word.我的代码现在只打印最后一个字母,而不是最后一个单词。 How do I get my code to print the last word?如何让我的代码打印最后一个字?

Your problem is doing some_string[-1] on a string which takes only the last letter of that string.你的问题是在一个字符串上做 some_string[-1] ,它只需要该字符串的最后一个字母。 Solution is to use some_string.split() on your string to split it by space into a list of values and then take the last element of that list with some_list[-1].解决方案是在字符串上使用 some_string.split() 将其按空格拆分为值列表,然后使用 some_list[-1] 获取该列表的最后一个元素。

names_list = []
for i in range(0, 5):
    names_list.append(input("Name: "))
sorted_last_names = sorted([name.split()[-1] for name in names_list])
print(sorted_last_names)

This is easier than the answer above.这比上面的答案更容易。 For me, it's more clear this way.对我来说,这样更清楚。

name_list = []
for i in range (5):
    input_name = input("Name: ")
    name_list.append(input_name.split()[-1])
   

name_list.sort()
print(name_list)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM