Formatting a list of text into columns

前端 未结 8 1048
我在风中等你
我在风中等你 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:36

    Here is an extension of the solution provided by gimel, which allows to print equally spaced columns.

    def fmtcols(mylist, cols):
        maxwidth = max(map(lambda x: len(x), mylist))
        justifyList = map(lambda x: x.ljust(maxwidth), mylist)
        lines = (' '.join(justifyList[i:i+cols]) 
                 for i in xrange(0,len(justifyList),cols))
        print "\n".join(lines)
    

    which returns something like this

    ACM:Aircraft Mechanic BC:Body Combat
    BIO:Biology CBE:Combat Engineer
    CHM:Chemistry CMP:Computers
    CRM:Combat Rifeman CVE:Civil Engineer
    DIS:Disguise ELC:Electronics ... ...`

    0 讨论(0)
  • 2021-02-07 09:40
    data = [ ("1","2"),("3","4") ]
    print "\n".join(map("\t".join,data))
    

    Not as flexible as the ActiveState solution, but shorter :-)

    0 讨论(0)
提交回复
热议问题