提问人:momoshki 提问时间:5/26/2023 最后编辑:momoshki 更新时间:5/26/2023 访问量:31
使用嵌套列表创建文凭 ( Python )
creating diploma using nested lists ( Python )
问:
我的拼贴教授要求制作一个文凭,其中包含 2 个列表 [coruses 和 students],并在其中嵌套 5 组,每组 5 名学生,并在其中填写他们的名字,每个学生有 5 个信息(任何),全部使用嵌套列表。但后来说,用任何你能做的事去做。
我尝试在列表中执行此操作,并达到此目的,如果我附加任何输入,孔编程就会充满错误
首先有可能吗?
diploma = []
std = []
less_than_15 = []
for i in range(5):
std.append(list(str(i)))
std[i].remove(str(i))
std[i].append(list(str(i)))
std[i][0].remove(str(i))
std[i][0].append(list(str(i)))
std[i][0][0].remove(str(i))
答:
0赞
Waqar
5/26/2023
#1
由于以下原因,您的代码将无法按预期的方式工作:
您正在为每个字符串创建列表,而不是列表列表 学生和小组。您正在删除元素并将其附加到 以令人困惑和不必要的方式列出。您没有填写 问题陈述要求的学生姓名和信息
我来为你写一个代码。
对于我所发现的。
courses = []
students = (5,5,5) # it has 5 rows, each with 5 sub-rows, each with 5 elements
例:
你可以这样填写它:
student = [
#first group
[
["student1", 14, "male", "B-", "math"],
[ ],
[ ],
[ ],
[ ]
],
#second group
and so on
]
这是您需要的所有代码
for i in range(len(students)):
print(f"Group {i+1}:")
for j in range(len(students[i])):
print(f"Student {j+1}: {', '.join(str(x) for x in students[i][j])}")
实现相同代码的另一种方法是使用随机 Python 库:
这是代码
import random
# Define the courses list
courses = ["Math", "Science", "English", "History", "Art"]
# Define some sample names and infos
names = ["Alice", "Bob", "Charlie","Paul", "Quinn"]
infos = ["Age: 18", "Gender: Female", "Grade: A+", "Course: Math", "Hobby: Painting"]
# Create an empty list for students
students = []
# Loop over 5 groups
for i in range(5):
# Create an empty list for each group
group = []
# Loop over 5 students in each group
for j in range(5):
# Create an empty list for each student
student = []
# Append a random name to the student list
student.append(random.choice(names))
# Loop over 4 infos for each student
for k in range(4):
# Append a random info to the student list
student.append(random.choice(infos))
# Append the student list to the group list
group.append(student)
# Append the group list to the students list
students.append(group)
# Print the diploma
print("Diploma")
print("Courses: ", ", ".join(courses))
print("Students:")
for i in range(len(students)):
print(f"Group {i+1}:")
for j in range(len(students[i])):
print(f"Student {j+1}: {', '.join(str(x) for x in students[i][j])}")
评论
0赞
momoshki
5/26/2023
谢谢,我会尝试阅读它并很好地理解它..
评论