2015-12-28 42 views
4

在這一節,他們希望我們創建該表:自動化無聊的東西第6章表打印機幾乎完成

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

它必須是合理的權利,並輸入資料表。這裏是我的代碼:

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

您是否嘗試過加盟第一? –

+0

你能多解釋一下嗎?你的意思是在打印函數的結尾還是在for循環中? –

+0

我現在試過了,但得到了參數錯誤。 –

回答

2

下面是一個替代方法,也許你可以應用到你自己的代碼。我第一次採取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)) 
+0

我們能不能簡化_,li部分?我使用了它,它看起來非常困難,甚至可能比我的問題還要多。你的方法比我自己想象的要先進得多,但如果你能多解釋一點,這將會有所幫助。 –

+0

我簡化了代碼,並添加了評論,以便您可以跟隨。希望這可以幫助! – vesche

+0

感謝您使問題變得更容易,我喜歡學習解決問題的新方法,但由於我一開始就使用zip()函數和其他內置函數或方法來解決問題,因此會挫敗實踐基礎知識的目的。 –

2

在這裏你去年輕的學徒:

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可能是不最佳的,副本存儲只是我想到的最快速的事情。

+0

你有一個輕微的語法錯誤的朋友,應該是'print(''*(maxlen - length)+ fruit,name,animal)'。 – vesche

+0

它與vesche對最後一行的更正有效,但關於水果,名稱和動物,它們是否被視爲列表?這是我第一次看到內置的zip功能,但我現在已經做了一些調查。我們可以認爲它是從其他列表製作迭代列表的捷徑嗎? –

+1

對不起,錯誤很明顯,我的頭仍然包裹在python 2. @StanleyWilkins zip在多個元組列表中轉換了多個列表,這對於一些迭代來說的確很方便。水果名稱和動物是循環迭代器,它們是單值;他們正在迭代的列表是tableData [n]。 –

1

首先加入的元素,然後找到最長的一個,然後你可以使用%*s寫行。更多的代碼註釋。

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

longest = 0 # to find the longest line 
lines = [] # to keep lines 

for elements in zip(tableData[0], tableData[1], tableData[2]): 

    # join elements in line - like 'apples' + ' ' + 'Alice' + ' ' + 'dogs' 
    line = ' '.join(elements) 

    # add line to the list 
    lines.append(line) 

    #print(line) # you can print it to see what you get 

    # find the longest line 
    length = len(line) 
    if length > longest: 
     longest = length 

#print('the longest:', longest) 

longest += 1 # to get one space more at left side 

# print lines using `%*s` 
# if `longest` is 21 then it will works as `%21s` 
for line in lines: 
    print('%*s' % (longest, line)) 
0

我有完全相反的問題:我已經想通了如何確定正確的說明理由的參數,以及如何右對齊的項目。然而,我很難在一行中打印幾個項目。我試過「end =''」,但輸出仍然看起來很奇怪。最後我嘗試連接打印在一行中的項目,並在循環中再次調用打印功能。它的工作。

花了我幾個小時來做​​這個簡單的練習,但它絕對是值得的!:)它真的很好回顧所有的增量改進最終使代碼工作!

這是我的代碼。希望這會有所幫助。

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

def printTable(tableData): 
    colWidths = [0] * len(tableData) 
    for i in range(len(tableData)): 
     for j in range(len(tableData[i])): 
      if colWidths[i] <= len(tableData[i][j]): 
       colWidths[i] = len(tableData[i][j]) 
      else: 
       colWidths[i] = colWidths[i] 

    for j in range(len(tableData[i])): 
     for i in range(len(tableData)): 
      print(''.join(tableData[i][j].rjust(colWidths[i] + 1)), end = '') 
      #the "+ 1" is used to allow for a space in between 
      print() 

printTable(tableData) 

順便說一句,我很驚訝,

for j in range(len(tableData[i])): 
    for i in range(len(tableData)): 

實際工作。

在這種情況下,不應該總是在j之前使用i嗎?這對我來說似乎是違反直覺的,但無論如何嘗試了這個奇蹟般的工作。

-2
#! python3 
# Table Printer 1 

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

def printTable(data): 
    colWidths = [0] * len(data) 
    for y in range(len(data[0])): 
     for x in range(len(data)): 
      colWidths[x] = len(max(data[x], key = len)) 
      print(data[x][y].rjust(colWidths[x]), end = ' ') 
     print() 

printTable(tableData) 


#! python3 
# Table Printer 2 

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

def printTable(data): 
    colWidths = [0] * len(data) 
    for x in range(len(data)): 
     for y in range(len(data[0])): 
      if len(data[x][y]) > colWidths[x]: 
       colWidths[x] = len(data[x][y]) 
    for y in range(len(data[0])): 
     for x in range(len(data)): 
      print(data[x][y].rjust(colWidths[x]), end = ' ') 
     print() 

printTable(tableData) 
+1

嗨測試,你能開發你在這裏做什麼來回答這個問題嗎?這是絕對不清楚的。 –

+1

你能否給你的代碼添加一些上下文? – ppperry

0

這是一個解決方案。即使內部列表中沒有更改,或內部列表中的所有元素都沒有更改(因爲所有內部列表都具有相同的元素數量),它也可以工作。

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

col_widths = list() 
for i, record in enumerate(tableData): 
    col_widths.insert(i, max(len(item) for item in record)) 

for i in range(len(tableData[0])): 
    print(' '.join(record[i].rjust(col_widths[j]) for j, record in enumerate(tableData))) 
0
#! python3 
#table printer prints takes a list of lists of strings and displays it in a 
#well-organized table with each column right-justified. 

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

def printTable(data): 
    #in this section we are creating a list containing each column's width 
    colWidths = [0] * len(data) 
    for m in range(len(colWidths)): 
     for n in range(len(data[0])): 
      if colWidths[m] < len(data[m][n]): 
       colWidths[m] = len(data[m][n]) 
    #optionally you can also print colWidths for a better understanding 
    #print(colWidths) will output [8, 5, 5] 

    #this section of the code helps arranging the list in a table format 
    for u in range(len(data[0])): 
     for v in range(len(data)): 
      print(data[v][u].rjust(colWidths[v] + 1), end='') 
     print() 

printTable(tableData) 
0

根據作者的提示:

「提示:您的代碼必須首先找到最長的字符串中的每個內部列表,這樣整列可夠寬()函數可以以colWidths = [0] * len(tableData)開頭,它將創建一個列表,其中包含相同數量的字符串0值作爲tableData中內部列表的數量。這樣,colWidths [0]可以將最長字符串的寬度存儲在tableData [0],colWidths [1]可以在tableData [1]中存儲最長字符串的寬度,依此類推。然後,您可以找到colWidths列表中的最大價值,找出整數寬度傳遞到rjust()字符串方法「

這裏是我的回答:

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


def table_printer(tab_data): 
    col_widths = [0] * len(tab_data) # creates 3 lists based on the list length 
    for j in range(len(tab_data[0])): # finds a length of 4 items (aka rows) 
     for i in range(len(tab_data)): # finds a length of 3 items (aka columns) 
      col_widths[i] = len((max(tab_data[i], key=len))) # sets the column width to the maximum length of an item in the list 
      a = tab_data[i][j] 
      print(a.rjust(col_widths[i]), end=" ") # every time we print a column, we rjust it to the max width. 
     print("\n") 


table_printer(tableData) 
0

因此,這是什麼我結束了with..without太多互聯網的幫助。但是,這種打印行很爛。我喜歡上面的一些內容,但不打算跟風。

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

def printTable(): 
    colWidths=[0]*len(tableData) 
    for i in range(len(tableData)): 
     for x in range(len(tableData[i])): 
      if colWidths[i]<len(tableData[i][x]): 
       colWidths[i]=len(tableData[i][x]) 
    for x in range(len(tableData[i])): 
     print(tableData[0][x].rjust(colWidths[0]+1) + tableData[1][x].rjust(colWidths[1]+1) + tableData[2][x].rjust(colWidths[2]+1)) 

printTable() 

打印出來是正確的,但我不喜歡它如何不允許動態使用。回到d打印線上的原料板。

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

def printTable(data): 
    for j in range(len(data[0])): 
     for i in range(len(data)): 
      #This line finds the longest item for each list and its length 
      x = len(max(data[i], key=len)) 
      print(data[i][j].rjust(x), end=' ') 
     print() 

printTable(tableData) 
0

以下是我如何使用本書中使用的提示和唯一信息。

無論TableData中有多少個子列表,也無論每個子列表中有多少個項目,此代碼都可以工作。

我在循環中使用了一個循環來實現這一點,並在每個打印項目之後打印一個空格。如果它是最後一個類別項目,則打印一個新行。

tableData = [['apples', 'oranges', 'cherries', 'banana','orange'], 
      ['Alice', 'Bob', 'Carol', 'David','Phillip'], 
      ['dogs', 'cats', 'moose', 'goose','anteater'], 
      ['poop','pee','semen','mucus','blood'], 
      ['mitsubishi','honda','toyota','ford','range rover']] 


def printTable(table): 
    colWidths = [0] * len(table) 
    for i in range(len(table)): 
     for x in table[i]: 
      if len(x) > colWidths[i]: 
       colWidths[i] = len(x) 
    print(colWidths) 

    for i in range(len(table[0])): 
     for x in range(len(table)): 
      print(table[x][i].rjust(colWidths[x]),end = ' ') 
      if x == len(table)-1: 
       print('\r') 



printTable(tableData) 


''' 
table[0,0] + table [1,0] + table [2,0] 
table[1,0] + table [1,1] 

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



def printTable(): 
#List colWidth contains the longest string in each of the inner lists 
colWidth=[0]*len(tableData) 

n=0 
#To find the longest string in each of the inner lists and store in 
    colWidth 
for li in tableData: 
    num=0 
    for j in li: 
     if(num<len(j)): 
      num=len(j) 
    colWidth[n]=num 
    n=n+1 

#To find the largest value in the colWidths list to find out what integer 
width to pass to the rjust() string method. 
c=0 
for i in colWidth: 
    if(c<i): 
     c=i 

#To print the data 
for m in range(len(tableData[0])): 
    for n in range(len(tableData)): 
     print (tableData[n][m]).rjust(c), 
    print('') 

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

def printTable(list): 
    len_list = [] 
    for i in range(len(list)): 
     len_list.append(len(max(list[i], key=len))) 
    for m in range(len(list[i])): 
     for i in range(len(list)): 
      print(list[i][m].rjust(len_list[i]+1), end = "") 
     print() #to add a new line 

printTable(tableData) 
0

我認爲最簡單的解決辦法是找到的最大大小字符串的整個列表的長度(內部和outter),然後將其設置爲論據右對齊方式(rjust() )然後根據問題使用循環打印列表值。

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


innerlen=0 

for m in tableData: 
    for n in m: 
     if innerlen < len(n): 
      innerlen = len(n) 




for m in range(len(tableData[0])): 
    for n in range(len(tableData)): 
     print(tableData[n][m].rjust(innerlen),end="") 

    print("") 
0

這裏是我的方法來練習:

#!/usr/bin/env python3 

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

def printTable(): 
    colWidths = [0] * len(tableData) 

    # find longest word in each list, convert to int 
    # and add to colWidths var 
    for i in range(len(tableData)): 
     for l in tableData[i]: 
      if len(l) >= colWidths[i]: 
       colWidths[i] = len(l) 
    # print and justify using the values from colWidths + 1 
    for t in range(4): 
     print(tableData[0][t].rjust(colWidths[0]+1) + \ 
       tableData[1][t].rjust(colWidths[1]+1) + \ 
       tableData[2][t].rjust(colWidths[2]+1)) 

printTable() 
0
def print_table(tab): 
    for j in range(len(tab[0])): 
     for i in range(len(tab)): 
      m = max([len(s) for s in tab[i]]) 
      print(tab[i][j].rjust(m), end=' ') 
     print('') 


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

print_table(tableData) 
0

也許不是最好的方式,但這裏是我的解決方案的任務:

def printtable(listlist): 
    # variable stores the maximum length of the words in the lists 
    lenghtCounter = 0 #8 
    listCounter = 0 #3 
    dict = {} 

    for list in listlist: 
     listCounter += 1 
     wordcounter = 0 

     for pos in range(len(list)): 
      wordcounter += 1 

      for word in list[pos:len(list):len(list)]: 
       dict.update({list[pos]: pos}) 

       # length counter will store the longest value 
       if len(word) > lenghtCounter: 
        lenghtCounter = len(word) 

    for i in range(wordcounter): 
     line = [] 
     strline = '' 

     for k, v in dict.items(): 
      if v == i: 
       line.append(k) 
       strline.join(k.ljust(lenghtCounter)) 

     for el in line: 
      strline += el.ljust(lenghtCounter + 5) 
     print(strline) 

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

printtable(tableData) 
相關問題