将Python二维矩阵/列表转为表格

2 投票
4 回答
1921 浏览
提问于 2025-04-18 00:02

我该如何把这个:

students = [("Abe", 200), ("Lindsay", 180), ("Rachel" , 215)]

变成这个:

Abe     200
Lindsay 180
Rachel  215

补充:这个方法应该适用于任何大小的列表。

4 个回答

0

对于Python 3.6及以上版本,你可以使用f-string来实现一行代码的写法,这个方法是Ashwini Chaudhary回答中的一种简化方式:

>>> students = (("Abe", 200), ("Lindsay", 180), ("Rachel" , 215))
>>> print('\n'.join((f'{a:<7s} {b}' for a, b in students)))
Abe     200
Lindsay 180
Rachel  215

如果你不知道列表中最长字符串的长度,可以按照下面的方法计算出来:

>>> students = (("Abe", 200), ("Lindsay", 180), ("Rachel" , 215))
>>> width = max((len(s[0]) for s in students))
>>> print('\n'.join((f'{a:<{width}} {b}' for a, b in students)))
Abe     200
Lindsay 180
Rachel  215
0

使用 rjust 和 ljust:

for s in students:
    print s[0].ljust(8)+(str(s[1])).ljust(3)

输出结果:

 Abe     200
 Lindsay 180
 Rachel  215
0

编辑:有人修改了问题的一个关键细节 Aशwini चhaudhary 给出了一个很棒的答案。如果你现在不打算学习或使用 string.format,那么有一种更通用的、算法性的解决问题的方法可以这样做:

for (name, score) in students:
    print '%s%s%s\n'%(name,' '*(10-len(name)),score)
5

使用字符串格式化

>>> students = [("Abe", 200), ("Lindsay", 180), ("Rachel" , 215)]
>>> for a, b in students:
...     print '{:<7s} {}'.format(a, b)
...
Abe     200
Lindsay 180
Rachel  215

撰写回答