简体   繁体   English

将 Python 2D 矩阵/列表变成表格

[英]Turn the Python 2D matrix/list into a table

How can I turn this:我怎样才能把这个:

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

into this:进入这个:

Abe     200
Lindsay 180
Rachel  215

EDIT: This should be able to work for any size list.编辑:这应该适用于任何大小的列表。

Use string formatting :使用字符串格式

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

EDIT: someone changed a key detail of the question Aशwini चhaudhary gives an excellent answer.编辑:有人更改了问题的关键细节Aशwini चhaudhary 给出了一个很好的答案。 If you are not in a position of learning/using string.format right now then a more universal/algorithmic way of solving the problem is like this:如果您现在不处于学习/使用 string.format 的位置,那么解决问题的更通用/算法的方法是这样的:

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

Use rjust and ljust:使用 rjust 和 ljust:

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

Output:输出:

 Abe     200
 Lindsay 180
 Rachel  215

For Python 3.6+ you can use f-string for a one-line version of Ashwini Chaudhary's answer:对于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

If you don't know the length of the longest string in your list you can calculate it as below:如果您不知道列表中最长字符串的长度,您可以如下方式计算

>>> 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM