Formatting a list of text into columns

前端 未结 8 1046
我在风中等你
我在风中等你 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 ... ...`

提交回复
热议问题