此程序与预期功能一起使用
- 使用用户输入创建一个列表以生成五个名称,
- 使用用户输入创建一个列表,以数字形式生成五个分数/等级。
- 创建第三个列表,将列表中的每个元素组合在一起 第一个列表在第二个列表中具有相应的索引位置。
例如:
Student_Names= []
Marks= []
StudentNames_Marks= []
for i in range (5): #Go through and append the student names into Student_Names list by requesting the information five times and appending each time
_name= input("Please enter a name for the student records list. ")
Student_Names.append(_name)
_sum=0 #This is used to create a second for loop under the event that they do not enter a digit within the first list, allowing them to continue forward
for i in range (5):
_marks= input("Please enter marks in digit format. ")
if _marks.isalpha():
print("Please enter a digit, such as 10 instead of ten.")
_sum=_sum+1 #Add one to the sum to create the amount of loops in the second for loop
else:
Marks.append(_marks)
if _sum>0:
for i in range(_sum):
_marks=input("Please enter marks in digit format. ")
if _marks.isalpha():
print("Please enter a digit, such as 10 instead of ten. The program will not run properly. Please restart the program.")
else:
Marks.append(_marks)
_numbera= len(Student_Names) #Using the lengths of the list to determine the length of the for loop
_numberb= len(Marks)
_length= _numbera+_numberb
for i in range (5):
_value=Student_Names.pop()
StudentNames_Marks.append(_value)
_value=Marks.pop()
StudentNames_Marks.append(_value)
print(StudentNames_Marks)
如果在提示中输入以下内容,则将在控制台上生成以下内容:
Name prompt responses: James, Jack, Ivy, Eva, Lee Marks: 10, 64, 36, 86, 35 Student_Names= ['James', 'Jack', 'Ivy', 'Eva', 'Lee'] Marks= ['10', '64', '36', '86', '35'] StudentNames_Marks= ['Lee', '35', 'Eva', '86', 'Ivy', '36', 'Jack', '64', 'James', '10'
但是,我坚持开发最后一步。我目前已经得到一个列表,它以正确的顺序从前两个列表中获取元素,如上所述。我不确定如何使用破折号组合最终列表中的元素,所以它看起来更像这样:
StudentNames_Marks= ['Lee- 35', 'Eva- 86', 'Ivy- 36', 'Jack- 64', 'James- 10']
我该如何着手做这样的事情?
请您参考如下方法:
使用 zip 和 list comprehension 的一行代码:
>>> ['-'.join(ele) for ele in zip(student_names, marks)]
在这里,zip 命令用于创建组合 student_name 和 marks 的元组,然后使用 join< 将它们连接在一起 函数。
#驱动程序值:
IN : student_names= ['James', 'Jack', 'Ivy', 'Eva', 'Lee']
IN : marks = ['10', '64', '36', '86', '35']
OUT : ['James-10', 'Jack-64', 'Ivy-36', 'Eva-86', 'Lee-35']
