[英]Used for loop to print the row count of the array then data duplicates base on length of my array, how do I print only 1 line of data in Python?
如何只打印一份数据? 我是一个完整的初学者。 这是我为添加数据所做的 Python 代码。
这是我目前的 output:
Row | Name | Age | Grade
1 jo 23 1
2 jo 23 1
1 ki 24 2
2 ki 24 2
这是我预期的 output:
Row | Name | Age | Grade
1 jo 23 1
2 ki 24 2
这是我的代码:
name = []
age = []
grade = []
record = []
rowCount = 0
choice = 1
while int(choice) != 0:
if int(choice) > 4 or int(choice) < 1:
choice = input ("Invalid input. Enter choice: ")
else:
print("Main Menu:")
print("1- Add")
print("2- Delete")
print("3- Edit")
print("4- Print Report")
print("0- End Program")
choice = input ("Enter choice: ")
if int(choice) == 1: #Add function
name.append(input("Input Name: "))
age.append(input("Input Age: "))
grade.append(input("Input Grade: "))
print ("Row | Name | Age | Grade")
for x, y, z in zip(name,age,grade):
for w in range(len(name)):
print(str(w+1) + " " + x + " " + y + " " + z)
w+1
elif int(choice) == 2: #Delete function
print("Delete func")
elif int(choice) == 3: #Update function
print("Edit func")
elif int(choice) == 4: #Print function
print("Print func")
print("Ending Program...")
对于zip(name, age, grade)
中的每个条目,您都有另一个嵌套循环(对于w
)。 这会导致程序为每个条目打印多行。 解决它的一种方法是在zip
中包含w
; 即,更换
for x, y, z in zip(name,age,grade):
for w in range(len(name)):
print(str(w+1) + " " + x + " " + y + " " + z)
w+1
和
for x, y, z, w in zip(name, age, grade, range(len(name))):
print(str(w+1) + " " + x + " " + y + " " + z)
您可以为每组数据使用列表列表,然后使用set function
例如:
students = []
...
while True:
name = input("Input Name: ")
age = input("Input Age: ")
grade = input("Input Grade: ")
student.append([name, age, grade])
然后,要仅获取列表列表中的唯一数据,您可以使用 set,但 set 不适用于列表列表,因此您可以迭代它并将每个列表视为一个元组,然后在元组上使用 set ,我改编自这个答案,即:
unique_students = set(tuple(row) for row in (students)))
现在您有了一个包含来自学生的唯一数据的新变量,您可以遍历它并根据需要打印数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.