我正在为一位老师写一个程序。教师应该询问学生的姓名,然后询问学生的成绩。这需要尽可能多的人,然后一旦教师输入'q',程序就会打算将学生的所有姓名和成绩打印在另一个顺序之上。这是我到目前为止所拥有的。问题是它没有打印所有的名称和等级,我试图看看如何将名称和等级存储在某种列表中。但我不知道如何。
while True:
students = raw_input("Please give me the name of the student (q to quit): ")
if students == 'q':
break
grade = raw_input("Please give me their grade: ")
print "Okay, printing grades!"
print "Student Grade"
print students, grade
答案 0 :(得分:1)
很容易,使用两个数组,压缩它们以获取元组列表然后下标元组:
students=[]
grades=[]
while True:
student = raw_input("Please give me the name of the student (q to quit): ")
if student == 'q':
for i in zip(students, grades):
print "Student: " + i[0] + ", Grade: " + i[1]
break
grade = raw_input("Please give me their grade: ")
students.append(student)
grades.append(grade)
或没有zip()
:
students=[]
grades=[]
while True:
student = raw_input("Please give me the name of the student (q to quit): ")
if student == 'q':
for i in range(len(students)):
print "Student: " + students[i] + ", Grade: " + grades[i]
break
grade = raw_input("Please give me their grade: ")
students.append(student)
grades.append(grade)
这些是与此计划相关的文档:
zip()
in Python 强> list.append()
in Python 强> 希望这有帮助!
答案 1 :(得分:0)
使用词典列表。这将允许您保留输入的顺序。
students_grades = []
while True:
data = {}
data["student_name"] = raw_input("Please give me the name of the student (q to quit): ")
if data["student_name"] == 'q':
break
data["grade"] = raw_input("Please give me their grade: ").capitalize()
students_grades.append(data)
print "Okay, printing grades!"
for data in students_grades:
print "{student_name}: {grade}".format(**data)
字符串上的format
方法允许您以各种方式替换字符串中的括号,其中一种方法允许您传入替换相应命名括号的kwargs。 splat运算符**
基本上采用字典并将其转换为函数kwargs,因此它相当于在这种情况下传入.format(student_name="...", grade="...")
。