我正在尝试将字符串值列表输出为2列格式。将字符串列表制作为“普通文本”的标准方法是使用 string.join 方法。但是,它只需要2个参数,因此我只能使用“\ n”创建一个列。我认为尝试创建一个只需在列之间添加选项卡的循环就可以了,但逻辑无法正常工作。
我发现ActiveState page有一种相当复杂的方法,但它是从4年前开始的。现在有一种简单的方法吗?
修改以下是我要使用的列表。
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"]
我只想将此列表输出为简单的2列格式以减少空间。理想情况下,列之间应该有一个标准的空间,但我可以使用它。
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
答案 0 :(得分:11)
由制表符分隔的两列连接成行。在 itertools 中查找迭代器等价物,以实现节省空间的解决方案。
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
...
哎呀......被S.Lott抓住了(谢谢)。
更通用的解决方案,处理任意数量的列和奇数列表。从S.lott略微修改,使用生成器来节省空间。
def fmtcols(mylist, cols):
lines = ("\t".join(mylist[i:i+cols]) for i in xrange(0,len(mylist),cols))
return '\n'.join(lines)
答案 1 :(得分:4)
这有效
it = iter(skills_defs)
for i in it:
print('{:<60}{}'.format(i, next(it, "")))
答案 2 :(得分:3)
这是冗长的,所以我将它分成两部分。
def columns( skills_defs, cols=2 ):
pairs = [ "\t".join(skills_defs[i:i+cols]) for i in range(0,len(skills_defs),cols) ]
return "\n".join( pairs )
显然,它可以作为单个loooong语句完成。
这也适用于奇数技能。
答案 3 :(得分:3)
这是gimel提供的解决方案的扩展,它允许打印等间距的列。
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)
返回类似这样的内容
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
...... ......
答案 4 :(得分:0)
data = [ ("1","2"),("3","4") ]
print "\n".join(map("\t".join,data))
不像ActiveState解决方案那么灵活,但更短: - )
答案 5 :(得分:0)
format_columns
函数应该执行您想要的操作:
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
这假设你有一个带有生成器的Python。
答案 6 :(得分:0)
我认为其中许多解决方案将两个独立的事物合二为一。
你想要:
以下是关于如何执行此操作的简单方法:
import sys
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"]
# The only thing "colform" does is return a modified version of "txt" that is
# ensured to be exactly "width" characters long. It truncates or adds spaces
# on the end as needed.
def colform(txt, width):
if len(txt) > width:
txt = txt[:width]
elif len(txt) < width:
txt = txt + (" " * (width - len(txt)))
return txt
# Now that you have colform you can use it to print out columns any way you wish.
# Here's one brain-dead way to print in two columns:
for i in xrange(len(skills_defs)):
sys.stdout.write(colform(skills_defs[i], 30))
if i % 2 == 1:
sys.stdout.write('\n')
答案 7 :(得分:0)
这也可能对您有帮助。
for i in skills_defs:
if skills_defs.index(i)%2 ==0:
print(i.ljust(30),end = " ")
else:
print(i.ljust(30))