嗨,我正在为Grok学习开发一个模块,创建一个程序时遇到了一个问题,该程序采用学生姓名的列表,并将每个姓名单独打印出来,并按字母顺序打印为班级名册(每个姓名都大写(。
#pseudo
# ask for students and store in 'students'
# split 'students', which is now a list
# sorts the list alphabetically
# print('Class roll')
# for i in students
# print i . capitalize
data = input('Students: ')
students = data.split()
students = students.sort()
print('Class Roll')
for i in students:
print(i.capitalize())
本质上,它给了我一个我不理解的错误信息:
Students: a c b d
Class Roll
Traceback (most recent call last):
File "program.py", line 13, in <module>
for i in students:
TypeError: 'NoneType' object is not iterable
评论很好。
这应该可以解决您的问题。只需删除等号,因为.sort((会转换列表本身。
data = input('Students: ')
students = data.split()
students.sort()
print('Class Roll')
for i in students:
print(i.capitalize())
当您对列表调用sort
时,它会原地排序,而不是返回已排序的列表。尝试不分配,即:
data = input('Students: ')
students = data.split()
students.sort() # this line is changed
print('Class Roll')
for i in students:
print(i.capitalize())