gpt4 book ai didi

python - 将文本列表格式化为列

转载 作者:bug小助手 更新时间:2023-10-28 10:46:06 32 4
gpt4 key购买 nike

我正在尝试将字符串值列表输出为 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

最佳答案

由制表符分隔的两列连接成行。在 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)

关于python - 将文本列表格式化为列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/171662/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com