gpt4 book ai didi

python - 在python中将三个数组加在一起形成一个数组

转载 作者:行者123 更新时间:2023-12-04 15:19:07 25 4
gpt4 key购买 nike

我有一个包含姓名、3 个科目和这 3 个科目的成绩的数组。总共的数据是:

[["Talha","Fazeel","Usayd","Mujtaba","Sufyan","Aukasha","Moiz","Mohid","Wasil"],
["Math","English","Science"],
[10,8,7,4,3,7,8,9,8],[8,8,5,0,9,8,7,5,7],[7,6,4,2,4,3,5,7,9] ]

我想要一个像这样在列中打印它们的程序

我做的程序是

Name=()
Subject=()
Marks=()
a=[["Talha","Fazeel","Usayd","Mujtaba","Sufyan","Aukasha","Moiz","Mohid","Wasil"],
["Math","English","Science"],
[10,8,7,4,3,7,8,9,8],[8,8,5,0,9,8,7,5,7],[7,6,4,2,4,3,5,7,9] ]
for r in a:
for c in r:
print(c,end="")
print()

它给出的输出太困惑了:

TalhaFazeelUsaydMujtabaSufyanAukashaMoizMohidWasil
MathEnglishScience
1087437898
885098757
764243579

谁能帮我解决一下?

最佳答案

首先我们将数据从数组a中分离出来:

names = a[0]
subjects = a[1]
grades = a[2:]

接下来我们打印第一行并调用 print() 以在末尾添加一个换行符:

print("Names", end=" ")
for i in range(len(subjects)):
print(subjects[i], end="\t")
print()

请注意在每次打印调用后使用 end= "\t" 参数在每个主题 \n 之后添加一个制表符

接下来,对于每个 name,我们打印姓名,对于每个科目,我们打印姓名的成绩:

for i in range(len(names)):
print(names[i], end="\t")
for j in range(len(subjects)):
print(grades[j][i], end = "\t")
print()

在每一行之后我们调用print()来添加一个换行符\n

或者,对于更复杂的解决方案,您可以使用 %s 来格式化带有额外空格的字符串并右对齐以获得更漂亮的输出:

a=[["Talha","Fazeel","Usayd","Mujtaba","Sufyan","Aukasha","Moiz","Mohid","Wasil"],
["Math","English","Science"],
[10,8,7,4,3,7,8,9,8],[8,8,5,0,9,8,7,5,7],[7,6,4,2,4,3,5,7,9] ]

names = a[0]
subjects = a[1]
grades = a[2:]

extra_spaces = 2
max_name_length = len(max(names, key=lambda item: len(item)))

first_col_indent = max_name_length + extra_spaces

print(f"%{first_col_indent}s" % "Names", end="")
for i in range(len(subjects)):
print(f"%{len(subjects[i])+extra_spaces}s" % subjects[i], end="")

print()
for i in range(len(names)):
print(f"%{first_col_indent}s" % names[i], end="")
for j in range(len(subjects)):
print(f"%{len(subjects[j])+extra_spaces}s" % grades[j][i], end = "")
print()

输出:

Names      Math  English  Science
Talha 10 8 7
Fazeel 8 8 6
Usayd 7 5 4
Mujtaba 4 0 2
Sufyan 3 9 4
Aukasha 7 8 3
Moiz 8 7 5
Mohid 9 5 7
Wasil 8 7 9

有关字符串格式化的更多信息,请查看this文档

关于python - 在python中将三个数组加在一起形成一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63722701/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com