我如何使用一个循环' 2个不同的列表

时间:2018-04-05 04:16:54

标签: python

我想在for循环中打印出一个句子,其中为每个不同的情况打印出不同的句子迭代,即我有两个不同的列表:student_result_reading和student_name

student_result_reading = []
student_name = []

while True:

   student_name_enter = input("Please enter student name: ")
   student_name.append(student_name_enter)

   student_enter = int(input("Please enter student result between 0 - 100%: "))
   student_result_reading.append(student_enter)

   continueask = input("Would you like to enter someone else? ")
   if continueask == "yes":
          continue
   else:
          break

for studread, studentname in student_result_reading, student_name:
   print("Student Name: {} | Test Name: Reading Test | Percentage Score: {}".format(studentname, studread))     

以下是我的两个问题:

  1. 当我输入2个或更多名称时,它们格式不正确。

  2. 当我输入1个名字时,我收到错误。

  3. 对任何解决方案的任何帮助表示赞赏。

7 个答案:

答案 0 :(得分:3)

您可以使用built-in function zip

for studread, studentname in zip(student_result_reading, student_name):
   print("Student Name: {} | Test Name: Reading Test | Percentage Score: {}".format(studentname, studread))

另外,如果您使用的是Python 2,可能会遇到问题,这两行:

student_name_enter = input("Please enter student name: ")

continueask = input("Would you like to enter someone else? ")

即如果您输入student name之类的内容作为学生姓名的输入,您将获得SyntaxErrorNameError。原因是,在Python 2中,input函数需要有效的Python表达式,在大多数情况下,字符串,如"student name",而不仅仅是student name。要使后面的表达式成为有效输入,可以使用函数raw_input

答案 1 :(得分:0)

我更喜欢按索引访问数组元素,如下所示:

for x in range(len(student_name)):
    print("Student Name: {} | Test Name: Reading Test | Percentage Score: {}".format(student_name[x], student_result_reading[x]))

答案 2 :(得分:0)

我在python中没有多少经验,但你可以做什么我保留一个学生数量的计数器,比如count_students

{{1}}

答案 3 :(得分:0)

如果你只输入两名学生,代码只会侥幸成功。主要问题是最后对for循环的误解。

for x, y in [1,2],[4,3]:
    print(x,y)

将打印

1,2
4,3

不会打印

1,4
2,3

如你所愿。这就解答了为什么在输入两个学生时看到错误格式的原因。您将要使用zip来加入两个列表,如另一个答案中所指出的那样。

zip([1,2],[4,3]) will equal [(1,4),(2,3)] 

所以你的for循环将按预期工作。

答案 4 :(得分:0)

使用以下方法生成错误:"输入"

我更换了" raw_input"。

您可以粘贴并运行此代码。

student_result_reading = []
student_name = []

while True:

   # student_name_enter = input("Please enter student name: ")
   student_name_enter = raw_input("Please enter student name: ")
   student_name.append(student_name_enter)

   # student_enter = int(input("Please enter student result between 0 - 100%: "))
   student_enter = int(raw_input("Please enter student result between 0 - 100%: "))
   student_result_reading.append(student_enter)

   # continueask = input("Would you like to enter someone else? ")
   continueask = raw_input("Would you like to enter someone else? ")

   if continueask == "yes":
          continue
   else:
          break

# for studread, studentname in student_result_reading, student_name:
#    print("Student Name: {} | Test Name: Reading Test | Percentage Score: {}".format(studentname, studread))
for studread, studentname in zip(student_result_reading, student_name):
   print("Student Name: {} | Test Name: Reading Test | Percentage Score: {}".format(studentname, studread))

答案 5 :(得分:0)

student_result_reading = {}
#Create a dictionary to store the students name, and their score 


while True:
       student_name_enter = input('Please enter a student name: ')
       #Ask the user for a student name 

       student_enter = int(input('Please enter a student result between 0 - 100%: '))
       #Have the user enter an integer for the student score

       student_result_reading[str(student_name_enter)] = student_enter
       #Make the key of the dict element the students name, value the students score

       continue_ask = input('Please enter yes to continue, or enter (q) to quit: ')
       #Prompt user to enter q to quit

       #If prompt == q, break out of the loop
       if continue_ask == 'q':
             break

for student, score in student_result_reading.items():
           #Use the .items() method of the dict to get the key, and corresponding value for each element in list 
           print('Student name: {0} | Test Name: Reading Test | Percentage Score: {1}'.format(student, score))

为简化此操作,您可以在字典中添加学生姓名,而不是使用两个列表。我们仍然运行while循环并询问用户输入的学生姓名和学生分数。然后我通过添加一个将成为学生姓名的密钥来改变字典,并将值设置为等于学生分数。然后我们可以通过输入q来提示用户继续或退出循环。我们可以使用字典的.items()方法迭代每个键及其对应的值。然后我们在同一个字典中获取您要查找的输出,而不是两个单独的列表,学生姓名是键,学生分数是值。这是输出:

 Please enter a student name: Random Student
 Please enter a student result between 0 - 100%: 90
 Please enter another student name and score, or enter (q) to quit: yes
 Please enter a student name: Random Student2
 Please enter a student result between 0 - 100%: 75
 Please enter another student name and score, or enter (q) to quit: q
 Student name: Random Student | Test Name: Reading Test | Percentage Score: 90
 Student name: Random Student2 | Test Name: Reading Test | Percentage Score: 75

答案 6 :(得分:0)

让我用更简单的例子解释一下:

pets = ['cat', 'dog']
ages = [5, 7]

for pet, age in pets, ages:
    print(pet, age)

这里印刷的是:

cat dog
5 7

关键问题是这里实际发生了什么。事实证明pets, ages实际上是一个元组。用逗号分隔的表达式称为expression-lists

它是一个包含2个列表的元组,看起来完全相同:(['cat', 'dog'], [5, 7])。所以当你迭代它时,下一个有趣的事情发生了:) Iterable unpacking!

基本上现在发生的是:

pet, age = ['cat', 'dog']

在下一次迭代中:

pet, age = [5, 7]

这就是你最初的惊人输出。

您遇到的第二个问题的原因是,如果您只提供一个名称,在第一次迭代中发生这种情况(让我们仍然使用带宠物的示例):

pet, age = ['python']

ValueError: need more than 1 value to unpack

要解决这两个问题,您可以使用built-in zip function

for studentname, studread in zip(student_name, student_result_reading):
   print('Student Name: {} | Test Name: Reading Test | Percentage Score: {}'.format(studentname, studread))

要格式化输出,您还可以使用所谓的f-strings,它们自Python 3.6起可用

for studentname, studread in zip(student_name, student_result_reading):
   print(f'Student Name: {studentname} | Test Name: Reading Test | Percentage Score: {studread}')