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
The format_columns
function should do what you want:
from __future__ import generators
try: import itertools
except ImportError: mymap, myzip= map, zip
else: mymap, myzip= itertools.imap, itertools.izip
def format_columns(string_list, columns, separator=" "):
"Produce equal-width columns from string_list"
sublists= []
# empty_str based on item 0 of string_list
try:
empty_str= type(string_list[0])()
except IndexError: # string_list is empty
return
# create a sublist for every column
for column in xrange(columns):
sublists.append(string_list[column::columns])
# find maximum length of a column
max_sublist_len= max(mymap(len, sublists))
# make all columns same length
for sublist in sublists:
if len(sublist) < max_sublist_len:
sublist.append(empty_str)
# calculate a format string for the output lines
format_str= separator.join(
"%%-%ds" % max(mymap(len, sublist))
for sublist in sublists)
for line_items in myzip(*sublists):
yield format_str % line_items
if __name__ == "__main__":
skills_defs = ["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","EQ:Equestrian", "FO:Forward Observer",
"FOR:Forage", "FRG:Forgery", "FRM:Farming", "FSH:Fishing",
"GEO:Geology", "GS:Gunsmith", "HW:Heavy Weapons", "IF:Indirect Fire",
"INS:Instruction", "INT:Interrogation", "JP:Jet Pilot", "LB:Longbow",
"LAP:Light Aircraft Pilot", "LCG:Large Caliber Gun", "LNG:Language",
"LP:Lockpick", "MC:Melee Combat", "MCY:Motorcycle", "MEC:Mechanic",
"MED:Medical", "MET:Meterology", "MNE:Mining Engineer",
"MTL:Metallurgy", "MTN:Mountaineering", "NWH:Nuclear Warhead",
"PAR:Parachute", "PST:Pistol", "RCN:Recon", "RWP:Rotary Wing Pilot",
"SBH:Small Boat Handling","SCD:Scuba Diving", "SCR:Scrounging",
"SWM:Swimming", "TW:Thrown Weapon", "TVD:Tracked Vehicle Driver",
"WVD:Wheeled Vehicle Driver"]
for line in format_columns(skills_defs, 2):
print line
This assumes that you have a Python with generators available.