Formatting a list of text into columns

前端 未结 8 1049
我在风中等你
我在风中等你 2021-02-07 08:34

I\'m trying to output a list of string values into a 2 column format. The standard way of making a list of strings into \"normal text\" is by using the string.join

8条回答
  •  再見小時候
    2021-02-07 09:27

    Two columns, separated by tabs, joined into lines. Look in itertools for iterator equivalents, to achieve a space-efficient solution.

    import string
    def fmtpairs(mylist):
        pairs = zip(mylist[::2],mylist[1::2])
        return '\n'.join('\t'.join(i) for i in pairs)
    
    print fmtpairs(list(string.ascii_uppercase))
    
    A   B
    C   D
    E   F
    G   H
    I   J
    ...
    

    Oops... got caught by S.Lott (thank you).

    A more general solution, handles any number of columns and odd lists. Slightly modified from S.lott, using generators to save space.

    def fmtcols(mylist, cols):
        lines = ("\t".join(mylist[i:i+cols]) for i in xrange(0,len(mylist),cols))
        return '\n'.join(lines)
    

提交回复
热议问题