我只是想知道当max()
和min()
是二维数组时该怎么做。我到处搜索,但确实设法找到了东西,但没有在相应的列中打印。
代码:
import random
students = int(input("How many students do you want to enter? \n Students: "))
Student_Count = [([0] * 4) for i in range(students)]
for a in range(students):
for b in range(4):
Student_Count[a][b] = random.randint(1,100)
Max = (list(map(max,Student_Count)))
Min = (list(map(min,Student_Count)))
for a in range (students):
print("Student", a + 1 , end = "\t\t\t")
for b in range (4):
print(Student_Count[a][b], end = "\t\t\t ") # the print of Random numbers
print()
print("_____________________________________________________________")
print("Highest", end = "\t\t\t\t")
for c in range (4):
print(Max[c], end = "\t\t\t ")
print()
print("Lowest", end = "\t\t\t\t ")
for c in range (4):
print(Min[c], end = "\t\t\t ")
输出:
How many students do you want to enter?
Students: 5
Student 1 84 84 49 48
Student 2 47 28 81 81
Student 3 89 31 95 79
Student 4 21 16 21 94
Student 5 87 51 63 14
_____________________________________________________________
Highest 84 81 95 94
Lowest 48 28 31 16
编辑:很抱歉这个模棱两可的问题
我对代码的预期结果是获取列表中每一列的最大值和最小值
答案 0 :(得分:2)
如果您的目标是每个位置的最小值,那么我认为最简单的方法是提取这些值的序列并将最小值/最大值应用于这些值:
import random
student_count = [
[random.randint(1, 100) for _ in range(4)]
for _ in range(int(input(
"How many students do you want to enter? \nStudents: "
)))
]
maxima = [max(student[i] for student in student_count) for i in range(4)]
minima = [min(student[i] for student in student_count) for i in range(4)]
sep = "\t"
for a, student in enumerate(student_count):
print(f"Student {a+1}{sep}{sep.join(map(str, student))}")
print("_____________________________________________________________")
print(f"Highest\t{sep}{sep.join(map(str, maxima))}")
print()
print(f"Lowest\t{sep}{sep.join(map(str, minima))}")
How many students do you want to enter?
Students: 9
Student 1 95 48 19 14
Student 2 37 79 62 93
Student 3 29 73 79 11
Student 4 76 18 9 88
Student 5 39 57 5 4
Student 6 42 92 6 31
Student 7 69 39 70 61
Student 8 16 89 33 76
Student 9 65 54 12 62
_____________________________________________________________
Highest 95 92 79 93
Lowest 16 18 5 4
答案 1 :(得分:1)
import random
students = int(input("How many students do you want to enter? \n Students: "))
Student_Count = [([0] * 4) for i in range(students)]
for a in range(students):
for b in range(4):
Student_Count[a][b] = random.randint(1,100)
Max = (list(map(max,Student_Count)))
Min = (list(map(min,Student_Count)))
print(Max)
print(Min)
for a in range(students):
print("Student", a + 1 , end = "\t\t\t")
for b in range (4):
print(Student_Count[a][b], end = "\t\t\t ") # the print of Random numbers
print()
print("_____________________________________________________________")
print("Highest", end = "\t\t\t\t")
for c in range(students):
print(Max[c], end = "\t\t\t ")
print()
print("Lowest", end = "\t\t\t\t ")
for c in range(students):
print(Min[c], end = "\t\t\t ")