How to print a list more nicely?

前端 未结 22 1294
北荒
北荒 2020-12-01 09:34

This is similar to How to print a list in Python “nicely”, but I would like to print the list even more nicely -- without the brackets and apostrophes and commas, and even b

22条回答
  •  心在旅途
    2020-12-01 10:15

    How about something like this?

    def strlistToColumns( strl, maxWidth, spacing=4 ):
    
    longest = max([len(s) for s in strl])
    width = longest+spacing
    
    # compute numCols s.t. (numCols-1)*(longest+spacing)+longest < maxWidth
    numCols = 1 + (maxWidth-longest)//width
    C = range(numCols)
    
    # If len(strl) does not have a multiple of numCols, pad it with empty strings
    strl += [""]*(len(strl) % numCols)
    numRows = len(strl)/numCols
    colString = ''
    
    for r in range(numRows):
        colString += "".join(["{"+str(c)+":"+str(width)+"}" \
            for c in C]+["\n"]).format(*(strl[numCols*r+c] \
            for c in C))
    
    return colString 
    
    
    if __name__ == '__main__':
    
    fruits = ['apple', 'banana', 'cantaloupe', 'durian', 'elderberry',         \
              'fig', 'grapefruit', 'honeydew', 'indonesian lime', 'jackfruit', \
              'kiwi', 'lychee', 'mango', 'orange', 'pomegranate', 'quince',    \
              'raspberry', 'tangerine', 'ugli fruit', 'watermelon', 'xigua',
              'yangmei', 'zinfandel grape']
    
    cols = strlistToColumns( fruits, 80 )
    
    print(cols)
    

    Output

    apple              banana             cantaloupe         durian
    elderberry         fig                grapefruit         honeydew
    indonesian lime    jackfruit          kiwi               lychee
    mango              orange             pomegranate        quince
    raspberry          tangerine          ugli fruit         watermelon
    xigua              yangmei            zinfandel grape
    

提交回复
热议问题