Python grok 学习列表

Python grok learning lists

你好,我正在开发一个 Grok 学习模块,这给我带来了一个问题,那就是创建一个程序,该程序采用 list 学生姓名并单独打印每个姓名,然后 按字母顺序作为一个class卷(每个名字大写)。

#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() # this line is changed
print('Class Roll')
for i in students:
  print(i.capitalize())

这应该可以解决您的问题。只需删除等号,因为 .sort() 会转换列表本身。

data = input('Students: ')
students = data.split()
students.sort()
print('Class Roll')
for i in students:
  print(i.capitalize())