我目前正在研究这个快速项目来学习,并且我半成功地将每个列表打印到列中,但在打印正确的列宽度时遇到了麻烦。
fruitNamePets = [ ['apples', 'oranges', 'cherries', 'bananas', 'pineapples', 'mangos'],
['Alice', 'Bob', 'Carol', 'David', 'Mike', 'Alex'],
['dogs', 'cats', 'moose', 'goose', 'deer', 'platypus']
]
def printTable(tableName):
colWidths = [0] * len(tableName)
for i in range(len(tableName[1])):
print ('')
for j in range(len(tableName)):
colWidths[j] = len(max(tableName[j])) + 2
print (str(tableName[j][i]).rjust(colWidths[j], ' '), end='')
printTable(fruitNamePets)
这是输出
apples Alice dogs
oranges Bob cats
cherries Carol moose
bananas David goose
pineapples Mike deer
mangos Alex platypus
如您所见,我将列右对齐,并将宽度设置为列表的最大长度 +2 个空格,但由于某种原因,中间列仅添加 +1 个空格。
感谢您的帮助,我是新来的,如果我发帖不正确,请告诉我!
最佳答案
问题是这一行:
colWidths[j] = len(max(tableName[j])) + 2
max(tableName[j])
返回 tableName[j]
中的“最大”值。对于字符串列表,这意味着按字母顺序排序最高的字符串。所以“菠萝”在第一列,“迈克”在第二列,“鸭嘴兽”在第三列。然后您将使用该单词的长度。
您真正想要的是最长单词的长度。试试这个:
colWidths[j] = max(len(word) for word in tableName[j]) + 2
len(word) for word in tableName[j]
是一个“列表理解”,它将字符串列表转换为字符串长度列表。列表理解是 Python 语言的重要组成部分,所以如果您还没有见过它,现在是学习它的好时机!
编辑
这是列表理解正在执行的操作的“手动”版本:
lengths = []
for word in tableName[j]:
lengths.append(len(word))
colWidths[j] = max(lengths) + 2
我们正在收集字符串的所有长度,然后找到这些长度的最大值。
关于python - 列宽 - 初学者Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38465368/