格式化 python defaultdict 结果并转换成字符串
Formatting python defaultdict results and converting into string
该代码段已经有效,但是,我一直在尝试根据我的需要格式化结果,但不知道如何设置。
from collections import defaultdict
data=defaultdict(int)
with open('data.txt') as f:
for line in f:
group, score, team = line.split(maxsplit=2)
data[(group.strip(),team.replace('\n','').strip())]+=int(score)
sorteddata = sorted([[k[0],v,k[1]] for k,v in data.items()], key=lambda x:x[1], reverse=True)
print ('\n'.join(map(str, sorteddata)))
样本文件(data.txt):
alpha 1 dream team
bravo 3 never mind us
charlie 1 diehard
delta 2 just cool
echo 5 dont do it
falcon 3 your team
lima 6 allofme
charlie 10 diehard
romeo 12 justnow
echo 8 dont do it
当前输出:
['echo', 13, 'dont do it']
['romeo', 12, 'justnow']
['charlie', 11, 'diehard']
['lima', 6, 'allofme']
['bravo', 3, 'never mind us']
['falcon', 3, 'your team']
['delta', 2, 'just cool']
['alpha', 1, 'dream team']
想要的输出:
echo 13 dont do it
romeo 12 justnow
charlie 11 diehard
lima 6 allofme
bravo 3 never mind us
falcon 3 your team
delta 2 just cool
alpha 1 dream team
尝试将最后一个 print
更改为:
print(*[" ".join(map(str, v)) for v in sorteddata], sep="\n")
这会打印:
echo 13 dont do it
romeo 12 justnow
charlie 11 diehard
lima 6 allofme
bravo 3 never mind us
falcon 3 your team
delta 2 just cool
alpha 1 dream team
或者:
for subl in sorteddata:
print(" ".join(map(str, subl)))
该代码段已经有效,但是,我一直在尝试根据我的需要格式化结果,但不知道如何设置。
from collections import defaultdict
data=defaultdict(int)
with open('data.txt') as f:
for line in f:
group, score, team = line.split(maxsplit=2)
data[(group.strip(),team.replace('\n','').strip())]+=int(score)
sorteddata = sorted([[k[0],v,k[1]] for k,v in data.items()], key=lambda x:x[1], reverse=True)
print ('\n'.join(map(str, sorteddata)))
样本文件(data.txt):
alpha 1 dream team
bravo 3 never mind us
charlie 1 diehard
delta 2 just cool
echo 5 dont do it
falcon 3 your team
lima 6 allofme
charlie 10 diehard
romeo 12 justnow
echo 8 dont do it
当前输出:
['echo', 13, 'dont do it']
['romeo', 12, 'justnow']
['charlie', 11, 'diehard']
['lima', 6, 'allofme']
['bravo', 3, 'never mind us']
['falcon', 3, 'your team']
['delta', 2, 'just cool']
['alpha', 1, 'dream team']
想要的输出:
echo 13 dont do it
romeo 12 justnow
charlie 11 diehard
lima 6 allofme
bravo 3 never mind us
falcon 3 your team
delta 2 just cool
alpha 1 dream team
尝试将最后一个 print
更改为:
print(*[" ".join(map(str, v)) for v in sorteddata], sep="\n")
这会打印:
echo 13 dont do it
romeo 12 justnow
charlie 11 diehard
lima 6 allofme
bravo 3 never mind us
falcon 3 your team
delta 2 just cool
alpha 1 dream team
或者:
for subl in sorteddata:
print(" ".join(map(str, subl)))