问题
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.
回答1:
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
回答2:
Use rjust and ljust:
for s in students:
print s[0].ljust(8)+(str(s[1])).ljust(3)
Output:
Abe 200
Lindsay 180
Rachel 215
回答3:
EDIT: someone changed a key detail of the question Aशwini चhaudhary gives an excellent answer. 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:
for (name, score) in students:
print '%s%s%s\n'%(name,' '*(10-len(name)),score)
回答4:
For Python 3.6+ you can use f-string for a one-line version of Ashwini Chaudhary's answer:
>>> 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:
>>> 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
来源:https://stackoverflow.com/questions/22670097/turn-the-python-2d-matrix-list-into-a-table