gpt4 book ai didi

Python:均匀分布具有不同字符串长度的输出数据

转载 作者:太空狗 更新时间:2023-10-29 22:15:32 37 4
gpt4 key购买 nike

我试图让我的输出数据看起来像这样:

-------------------------------------------------------
Grade Report for Programs
-------------------------------------------------------
Jacobson, Mark 19.0 <--- 20,17,20
Snurd, Mortimur 16.5 <--- 20,19,18,17,16,15,14,13
Luxemburg, Rosa 15.0 <--- 18,15,20,10,12
Atanasoff, John 20.0 <--- 20,20,20,20,20,20,20
Hopper, Grace 20.0 <--- 20,20,20,20,20,20
-------------------------------------------------------

但我不知道如何处理不同的名称长度。我的输出目前看起来像这样。


            Grade Report for Programs 
-------------------------------------------------------
Jacobson, Mark 19.0 <--- 20,17,20
Snurd, Mortimur 16.5 <--- 20,19,18,17,16,15,14,13
Luxemburg, Rosa 15.0 <--- 18,15,20,10,12
Atanasoff, John 20.0 <--- 20,20,20,20,20,20,20
Hopper, Grace 20.0 <--- 20,20,20,20,20,20
-------------------------------------------------------

我编写的程序是获取成绩分数的输入文件并收集数据并整齐地打印出平均值。

输入文件看起来像这样:

Mark Jacobson,20,17,20
Mortimur Snurd,20,19,18,17,16,15,14,13
Rosa Luxemburg,18,15,20,10,12
John Atanasoff,20,20,20,20,20,20,20
Grace Hopper,20,20,20,20,20,20

这里是我的代码,它收集姓名和分数,并打印出姓氏、名字、平均分数的数据,然后是得出平均分的实际分数。

file = input("Enter filename: ")

grade_file = open(file, 'r')

print()

print('---------------------------------------------------------')
print('\t\tGrade Report for Programs')
print('---------------------------------------------------------')

for text in grade_file:
end_of_name = text.find(',')
name_seperated = text.find(' ')

first_name = text[0:name_seperated]
last_name = text[name_seperated+1:end_of_name]

name_last_first = last_name + "," + " " + first_name

grades = text[end_of_name+1:]

start = 0
index = 0
sum_n = 0
average= 0
score = 0
count = 0

while index < len(grades):
if grades[index] == ',':
score = int(grades[start:index])
count += 1
sum_n = score + sum_n
start = index + 1
index += 1

count += 1

score = int(grades[start:index])
sum_n = score + sum_n
average = sum_n / count



print(name_last_first, " ", average, "<---", grades)


print('---------------------------------------------------------')


grade_file.close()

我只需要弄清楚如何使用偶数空格,这样它就可以像第一个输出那样生成偶数行和偶数列。非常感谢您的帮助!谢谢!

最佳答案

一种方法是使用 Python 的内置 C 样式格式。请注意,负的字段宽度表示该字段是左对齐的:

>>> print("%-30s %4.1f" % ("Jacobson, Mark", 19.0))
Jacobson, Mark 19.0
>>>

或者,您可以使用字符串 format 方法:

>>> print("{:30s} {:4.1f}".format("Jacobson, Mark", 19.0))
Jacobson, Mark 19.0
>>>

您还可以使用格式化字符串文字(f-strings):

>>> name = "Jacobson, Mark"
>>> average = 19.0
>>> print(f"{name:30s} {average:4.1f}")
Jacobson, Mark 19.0
>>>

关于Python:均匀分布具有不同字符串长度的输出数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33323715/

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