如何打印除标题行之外的每个列表的第一个索引?

2024-10-01 09:23:43 发布

您现在位置:Python中文网/ 问答频道 /正文

grades = [
    ['Student', 'Exam 1', 'Exam 2', 'Exam 3'],
    ['Thorny', '100', '90', '80'],
    ['Mac', '88', '99', '111'],
    ['Farva', '45', '56', '67'],
    ['Rabbit', '59', '61', '67'],
    ['Ursula', '73', '79', '83'],
    ['Foster', '89', '97', '101']
]

我想创建一个名为Students的新列表,其中包含除标题以外的所有学生姓名。你知道吗

我试过:

students = [item[0] for item in grades]

但这也给了我标题“学生”。你知道吗


Tags: 标题列表macitemstudent学生姓名grades
3条回答

扔掉第一行就行了。你知道吗

 students = students[1:]

你很接近。您只需限制语句中的grades

students = [item[0] for item in grades[1:]]

这将在grades上迭代,从第二个项目(索引为1)开始,直到最后(在:之后没有任何内容)。你知道吗

上面的解决方案使用列表压缩。这个解决方案使用了一种更通用的方式,您可以看到它是用其他编程语言编写的。你知道吗

  students = []
  for data in grades[1:]:
      students.append(data[0])

相关问题 更多 >