我使用以下代码生成2个列表,nameList和gradeList。
nameList[]
gradeList[]
for row in soup.find_all('tr'):
name = row.select('th strong')
grade = row.select('td label')
if grade and name:
if "/" in grade[0].text:
gradeList.append(grade[0].text)
nameShort = re.sub(r'^(.{20}).*$', '\g<1>...', str(name[0].text))
nameList.append(nameShort)
制作类似:
的内容nameList = [“grade 1”,”grade 2222222222”,”grade 3”]
gradeList = [“1/1”,”2/2”,”100000/100000”]
我希望程序能够并排打印2个干净列中的列表。在每列中,我希望数据对齐到左侧。列表(没有失败)将始终均匀填充。第一列(nameList)永远不会超过25个字符。我正在寻找的内容类似于以下内容:
Assignment Grade
0 grade 1 1/1
1 grade 2222222222 2/2
2 grade 3 100000/100000
我已经尝试过使用熊猫并且它有效,但格式化很奇怪且不合适。它不会像我想要的那样对齐左边。我相信这是因为两个列表中的数据都有不同的字符长度(如上所示)。
答案 0 :(得分:10)
使用str.format
:
nameList = ["grade 1", "grade 2222222222", "grade 3"]
gradeList = ["1/1", "2/2", "100000/100000"]
fmt = '{:<8}{:<20}{}'
print(fmt.format('', 'Assignment', 'Grade'))
for i, (name, grade) in enumerate(zip(nameList, gradeList)):
print(fmt.format(i, name, grade))
输出:
Assignment Grade
0 grade 1 1/1
1 grade 2222222222 2/2
2 grade 3 100000/100000
或者,您也可以使用printf
style formatting using % operator:
fmt = '%-8s%-20s%s'
print(fmt % ('', 'Assignment', 'Grade'))
for i, (name, grade) in enumerate(zip(nameList, gradeList)):
print(fmt % (i, name, grade))
答案 1 :(得分:5)
给出两个列表
nameList = ['grade 1','grade 2222222222','grade 3']
gradeList = ['1/1','2/2','100000/100000']
制表符分隔格式。使用zip()两个同时遍历两个列表
print 'Assignment \t\tGrade'
for n,g in zip(nameList,gradeList):
print n + '\t\t\t' + g
Assignment Grade
grade 1 1/1
grade 2222222222 2/2
grade 3 100000/100000
答案 2 :(得分:0)
您可以使用F字符串,我认为它变得更加清晰:
nameList = ["grade 1", "grade 2222222222", "grade 3"]
gradeList = ["1/1", "2/2", "100000/100000"]
# Table header
print(f'{"":<8} {"Assignment":<20} {"Grade":<20}')
# Table content
for i, (name, grade) in enumerate(zip(nameList, gradeList)):
print(f'{i:<8} {name:<20} {grade:<20}')
结果:
Assignment Grade
0 grade 1 1/1
1 grade 2222222222 2/2
2 grade 3 100000/100000