Python 将文本列表格式化为列

Python 将文本列表格式化为列,python,string,formatting,Python,String,Formatting,我正在尝试将字符串值列表输出为2列格式。将字符串列表转换为“普通文本”的标准方法是使用string.join方法。但是,它只需要2个参数,因此我只能使用“\n”创建一个列。我认为尝试创建一个循环,只需在列之间添加一个选项卡就可以了,但是逻辑没有正确工作 我发现了一个相当复杂的方法,但它是4年前的。现在有没有简单的方法 编辑这是我想要使用的列表 skills_defs = ["ACM:Aircraft Mechanic", "BC:Body Combat", "BIO:Biology",

我正在尝试将字符串值列表输出为2列格式。将字符串列表转换为“普通文本”的标准方法是使用string.join方法。但是,它只需要2个参数,因此我只能使用“\n”创建一个列。我认为尝试创建一个循环,只需在列之间添加一个选项卡就可以了,但是逻辑没有正确工作

我发现了一个相当复杂的方法,但它是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

不像ActiveState解决方案那样灵活,但更短:-)

两列由制表符分隔,连接成一行。在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.洛特抓住了(谢谢)

更一般的解决方案是处理任意数量的列和奇数列表。从中稍微修改,使用生成器以节省空间

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

这是一篇长篇大论,所以我要把它分成两部分

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 )
显然,它可以作为一个单独的looong语句来完成


这同样适用于奇数技能。

格式化列功能应该满足您的需要:

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
来自未来导入生成器
尝试:导入itertools
除了ImportError:mymap,myzip=map,zip
else:mymap,myzip=itertools.imap,itertools.izip
def格式_列(字符串_列表,列,分隔符=”):
“从字符串列表生成等宽列”
子列表=[]
#基于字符串列表项0的空字符串
尝试:
空字符串=类型(字符串列表[0])()
除索引器外:#字符串_列表为空
返回
#为每个列创建一个子列表
对于xrange中的列(列):
追加(字符串列表[列::列])
#查找列的最大长度
max_sublist_len=max(mymap(len,sublist))
#使所有列的长度相同
对于子列表中的子列表:
如果长度(子列表)
这假设您有一个带有生成器的Python。

这是可行的

it = iter(skills_defs)
for i in it:
    print('{:<60}{}'.format(i, next(it, "")))
it=iter(技能)
对我来说:

print(“{:这里是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:飞机机修工BC:身体对抗

BIO:Biology CBE:Combat Engineer

CHM:Chemistry-CMP:Computers

CRM:战斗步兵CVE:土木工程师

DIS:伪装ELC:电子设备

……我认为这些解决方案中的许多都是将两种不同的东西混为一谈

您想:

  • 能够将字符串强制为某个宽度
  • 打印表格
  • 下面是一个非常简单的方法:

    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')
    
    导入系统 技能_defs=[“ACM:飞机机修工”、“BC:身体对抗”、“BIO:生物学”, “CBE:作战工程师”、“CHM:化学”、“CMP:计算机”, “CRM:战斗步兵”、“CVE:土木工程师”、“DIS:伪装”, “ELC:电子学”、“EQ:马术”、“FO:前方观察员”, “用于:饲料”、“FRG:伪造”、“FRM:耕种”、“FSH:捕鱼”, “地理:地质学”、“GS:枪械匠”、“HW:重型武器”、“IF:间接火力”, “INS:指令”,“INT:询问”,“JP:喷气机飞行员”,“LB:长弓”, “LAP:轻型飞机飞行员”,“LCG:大口径火炮”,“LNG:语言”, “LP:开锁”、“MC:近战战斗”、“MCY:摩托车”、“MEC:机修工”, “医学:医学”、“气象:气象”、“MNE:采矿工程师”, “MTL:冶金”、“MTN:登山”、“NWH:核弹头”, “PAR:降落伞”,“PST:手枪”,“RCN:侦察”,“RWP:旋转翼飞行员”, “SBH:小船搬运”、“SCD:潜水”、“SCR:搜刮”, “SWM:游泳”,“TW:投掷武器”,“TVD:履带车辆驾驶员”, “WVD:轮式车辆驾驶员”] #“colform”所做的唯一一件事就是返回一个修改过的“txt”版本,即 #确保长度为“宽度”字符。它截断或添加空格 #根据需要在最后。 def colform(文本,宽度): 如果len(txt)>宽度: txt=txt[:宽度] elif len(txt)<宽度: txt=txt+(“”*(宽度-长度(txt))) 返回文本 #现在您有了colform,您可以使用它以任何方式打印列。 #这里有一种可以在两列中打印的方法: 对于xrange中的i(len(skills_defs)): 系统。
    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')
    
    for i in skills_defs:
    if skills_defs.index(i)%2 ==0:
        print(i.ljust(30),end = " ")
    else:
        print(i.ljust(30))