最好像这样的东西,但转换成人们称之为“老路”的东西。我正在尝试获得4个列表和4列标题。
到目前为止我(我是Python Illiterate,甚至认为这必须是Python)。
老路:print(" Student Report")
print("First Last DOB Rank")
print("--------------------------------")
ReadFile = open("mytext.txt","r")
with ReadFile as f:
[line.split() for line in f]
csv方式:
import csv
columns = [[] for _ in range(4)] # 4 columns expected
with open('path', rb) as f:
reader = csv.reader(f, delimiter=' ')
for row in reader:
for i, col in enumerate(row):
columns[i].append(col)
问题是如何将这个(请参阅下面的“样本报告”)放入4列的正确列表中。
谢谢:)
大约有30名假学生。
预期结果
Sample Report:
Student Report
First Last DOB Rank
--------------------------------------------
Coreena Delisio 8/7/1988 Freshman
William Barnes 10/26/1987 Junior
Joseph Mahan 9/18/1987 Senior
Susan Bevly 9/13/1987 Senior
End of Report
感谢大家的反馈和答案,我发现了它。
这是让我了解这个结果的代码。
## Report's Title
print(" Student Report")
## List Headers
F = ('First')
L = ('Last')
Birth = ('DOB')
Grade = ('Rank')
print('{:10} {:13} {:11} {:4}'.format(F, L, Birth, Grade))
print("--------------------------------------------")
ReadFile = open("input_file.txt","r")
## List of Lists Turned Into Columns
for line in ReadFile:
list = line.split(',')
First = list[0]
Last = list[1]
DOB = list[2]
Rank = list[3]
print('{:10} {:10} {:14} {:10}'.format(First, Last, DOB, Rank)) ## Columns
## 2 Added Blank Lines to Show Cleanliness
print()
print()
## End of Report
print('End of Report')
ReadFile.close()
答案 0 :(得分:0)
这有用吗?
padding = 5
n_columns = 4
columns = [['a','bc3','c','de'],['sadasd','sad','a','a'],['123123'],['123']]
max_entry_widths = [max(len(entry) for entry in column)
for column in columns]
column_widths = [width+padding for width in max_entry_widths]
n_rows = max(len(column) for column in columns)
row_str = ("{{: <{}}}" * n_columns).format(*column_widths)
rows = []
for row in range(n_rows):
entries = []
for col in range(n_columns):
try:
entries.append(columns[col][row])
except IndexError:
entries.append("")
rows.append(row_str.format(*entries))
print('\n'.join(rows))
# a sadasd 123123 123
# bc3 sad
# c a
# de a
答案 1 :(得分:0)
我不是这里的专家,你可以在定义填充时打印出一个字符串,以及它代表列的合理性。
如何执行此操作的示例是首先将每个字符串分配给如下值:
for lines in open('mytxt.txt'):
first = lines.split()[0]
last = lines.split()[1]
DOB = lines.split()[2]
rank = lines.split()[3]
接下来,您可以打印出来,同时定义第一列中可以打印的字符数(最适合浮动数字),以及彼此之间的列数:
print('{:20} {:20} {:20} {:20}'.format(first, last, DOB, rank))
我决定将每列可打印的字符数限制为20(这也是你的填充)。您也可以使用以下方式居中,右或左对齐:
##center_justify --> print('{:^20}'.format(center))
##right_justify --> print('{:>20}'.format(right))
##left_justify --> print('{:<20}'.format(left))