簡體   English   中英

我怎樣才能給這個列表的前半部分一個 A,給后半部分一個 B?

[英]How can I give an A to first half of this list and a B to the second half?

我正在做一個作業,告訴我按字母順序對這個學生列表進行排序,然后在列表的前半部分打印“Name you get an A”,在列表的后半部分打印“Name you get a B”。 我按字母順序排序,但不知道如何拆分列表

students = ['john','henry', 'abigail', 'zach', 'taylor', 'beatrice']
students = [student.capitalize() for student in students]
sorted_list = sorted(students)
print(sorted_list)

擴展馬蒂亞斯的評論,你可以做這樣的事情。 您首先迭代前半部分並打印名稱,然后迭代另一半部分。

students = ['john','henry', 'abigail', 'zach', 'taylor', 'beatrice']
for a_student in students[:len(students)//2]:
    print(f"{a_student.capitalize()} you get an A")
for b_student in students[len(students)//2:]:
    print(f"{b_student.capitalize()} you get a B")

這輸出:

John you get an A
Henry you get an A
Abigail you get an A
Zach you get a B
Taylor you get a B
Beatrice you get a B

一種更緊湊但不可讀的方法是直接在列表中制作作業文本並打印它們。

students = ['john','henry', 'abigail', 'zach', 'taylor', 'beatrice']
assignments = [f"{name.capitalize()} you get an A" if i < len(students)//2 else f"{name.capitalize()} you get a B" for i, name in enumerate(students)]
print('\n'.join(assignments))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM