你可以帮我解决这个问题吗?

时间:2017-09-28 01:27:04

标签: python-3.x while-loop

我有这个程序:

n = []
m = []

name = input("Enter student's names (separated by using commas) : ")
mark = input("Enter student's marks (separated by using commas) : ")
(n.append(name))
(m.append(mark))

total = 0
index = 0
while index < len(name) :
    print("name:",name[index],'mark:',mark[index])
    index +=1

它出现了这样:

Enter student's names (separated by using commas) : a,s,d
Enter student's marks (separated by using commas) : 1,2,3
name: a mark: 1
name: , mark: ,
name: s mark: 2
name: , mark: ,
name: d mark: 3

如何制作它只是这样:

Enter student's names (separated by using commas) : a,s,d
Enter student's marks (separated by using commas) : 1,2,3
name: a mark: 1
name: s mark: 2
name: d mark: 3

1 个答案:

答案 0 :(得分:1)

您需要使用拆分功能创建名称并标记为数组。

name = input("Enter student's names (separated by using commas) : ")
mark = input("Enter student's marks (separated by using commas) : ")

name = name.split(',')
mark = mark.split(',')
total = 0
index = 0
while index < len(name) :
    print("name:",name[index],'mark:',mark[index])
    index +=1

输出

$ python3 test.py 
Enter student's names (separated by using commas) : as,we,re
Enter student's marks (separated by using commas) : 1,2,3
name: as mark: 1
name: we mark: 2
name: re mark: 3

如果您想维护空列表,请执行以下操作:

n = []
m = []
name = input("Enter student's names (separated by using commas) : ")
mark = input("Enter student's marks (separated by using commas) : ")
(n.extend(name.split(',')))
(m.extend( mark.split(',')))
total = 0
index = 0
while index < len(n) :
    print("name:",n[index],'mark:',m[index])
    index +=1