自动完成无聊的工作第六章桌上打印机

2024-05-13 18:54:42 发布

您现在位置:Python中文网/ 问答频道 /正文

在本节中,他们希望我们创建此表:

    apples Alice dogs
     oranges Bob cats
 cherries Carol moose
   banana David goose

它必须向右对齐,输入是tableData。这是我的代码:

tableData=[['apples', 'oranges', 'cherries', 'banana'],
        ['Alice', 'Bob', 'Carol', 'David'],
        ['dogs', 'cats', 'moose', 'goose']]
listlens=[]
tour=0
lists={}
for m in tableData:
    total=0
    tour+=1
    for n in m:
        total+=len(n)
        lists["list:",tour]=total
    print("list",tour,total)    

itemcount=list(lists.values())
sortedlen=(sorted(itemcount,reverse=True))
longest=sortedlen[0]

#print (lists['list:', 1])
#print (longest)


for m in range(len(tableData[0])):
    for n in range(len(tableData)):
        print (tableData[n][m],end=" ")
        n+=1
    print ("".rjust(lists['list:', 1],"-"))
    m+=1

我差不多做完了,除了一件事,我不能证明这是正确的。这个输出是我迄今为止最接近的。

apples Alice dogs ---------------------------
oranges Bob cats ---------------------------
cherries Carol moose ---------------------------
banana David goose ---------------------------

如果我把rjust放在内部for循环中,输出会大不相同:

apples-------------------------- Alice-------------------------- dogs-------------------------- 
oranges-------------------------- Bob-------------------------- cats-------------------------- 
cherries-------------------------- Carol-------------------------- moose-------------------------- 
banana-------------------------- David-------------------------- goose-------------------------- 

Tags: mooseforlistslistbananabobprintalice
3条回答

这里有一个替代方法,也许你可以应用到你自己的代码中。我先把tableData整理成字典,这样就更容易使用了。在那之后,我找到了最长的字符列表。这让我们知道短名单应该走多远。最后,我打印出每个列表,根据与最长列表的差异在较短列表前面添加空格。

# orginal data
tableData=[['apples', 'oranges', 'cherries', 'banana'],
        ['Alice', 'Bob', 'Carol', 'David'],
        ['dogs', 'cats', 'moose', 'goose']]

# empty dictonary for sorting the data
newTable = {0:[], 1:[], 2:[], 3:[]}

# iterate through each list in tableData
for li in tableData:
    for i in range(len(li)):
        # put each item of tableData into newTable by index
        newTable[i].append(li[i])

# determine the longest list by number of total characters
# for instance ['apples', 'Alice', 'dogs'] would be 15 characters
# we will start with longest being zero at the start
longest = 0
# iterate through newTable
# for example the first key:value will be 0:['apples', 'Alice', 'dogs']
# we only really care about the value (the list) in this case
for key, value in newTable.items():
    # determine the total characters in each list
    # so effectively len('applesAlicedogs') for the first list
    length = len(''.join(value))
    # if the length is the longest length so far,
    # make that equal longest
    if length > longest:
        longest = length

# we will loop through the newTable one last time
# printing spaces infront of each list equal to the difference
# between the length of the longest list and length of the current list
# this way it's all nice and tidy to the right
for key, value in newTable.items():
    print(' ' * (longest - len(''.join(value))) + ' '.join(value))

我就是这样做的。

在代码的第一部分,我只是使用了他们给我们的提示。

第4章/练习项目/字符图片网格中,我们学习了如何“旋转”,然后打印列表列表。这对我的代码的第二部分很有用。

#!/usr/bin/python3
# you can think of x and y as coordinates

tableData = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dogs', 'cats', 'moose', 'goose']]

def printTable(table):
    # create a new list of 3 "0" values: one for each list in tableData
    colWidths = [0] * len(table)
    # search for the longest string in each list of tableData
    # and put the numbers of characters in the new list
    for y in range(len(table)):
        for x in table[y]:
            if colWidths[y] < len(x):
                colWidths[y] = len(x)

    # "rotate" and print the list of lists
    for x in range(len(table[0])) :
        for y in range(len(table)) :
            print(table[y][x].rjust(colWidths[y]), end = ' ')
        print()
        x += 1

printTable(tableData)

年轻的学徒来了:

tableData=[['apples', 'oranges', 'cherries', 'banana'],
    ['Alice', 'Bob', 'Carol', 'David'],
    ['dogs', 'cats', 'moose', 'goose']]
maxlen = 0
for fruit,name,animal in zip(tableData[0], tableData[1], tableData[2]):
    maxlen = max(len(fruit) + len (name) + len (animal), maxlen)
for fruit,name,animal in zip(tableData[0], tableData[1], tableData[2]):
    length = len(fruit) + len (name) + len (animal) 
    print ((' ' * (maxlen - length)) + fruit, name, animal)

循环确定maxlen可能不是最优的,复制粘贴只是我脑海中最快出现的事情。

相关问题 更多 >