在Python中,我有这样一个列表列表:
vote_count = [('Matthew', 5), ('Harry', 8)]
,我想打印这个列表,使第二列的数字左对齐,并在第一列中最长的字符串后面开始3个空格,像这样:
Matthew 5
Harry 8
目前,我的代码在两个左对齐的列中打印数组,但没有达到所需的规格。我应该如何改变我的print语句来做到这一点?
vote_count = [('Matthew', 5), ('Harry', 88)]
for i in vote_count:
print("%-10s" "%i" % (i[0], i[1]))
尝试以下操作,它首先使用生成器推导式确定最长长度,然后使用f-string相应地打印输出。
vote_count = [('Matthew', 5), ('Harry', 8)]
longest = max(len(name) for name, _ in vote_count)
for name, cnt in vote_count:
print(f'{name:{longest}} {cnt}')
# Matthew 5
# Harry 8
vote_count = [('Matthew', 5), ('MatthewMatthewHarryHarry', 20), ('Harry', 88)]
vote_count_new = []
maxlen = 0
space_dist = 3
maxlen = max([(len(i[0])+len(str(i[1]))) for i in vote_count])
for i in vote_count:
vote_count_new.append((i[0] + ' ' * ((maxlen - len(i[0]) - len(str(i[1]))) + (space_dist-1)), i[1]))
for i in vote_count_new:
print(i[0], i[1])
SCENARIO 1 Output:
vote_count = [('Matthew', 5), ('MatthewMatthewHarryHarry', 20), ('Harry', 88)]
Matthew 5
MatthewMatthewHarryHarry 20
Harry 88
SCENARIO 2 Output:
vote_count = [('Matthew', 5), ('MatthewMatthewHarryHarry', 20), ('Harry', 88), ('MatthewMatthewHarryHarry', 123456789)]
Matthew 5
MatthewMatthewHarryHarry 20
Harry 88
MatthewMatthewHarryHarry 123456789