我们说我有这样的事情:
counts = {"chuck" : 1 , "annie" : 42, "jan" : 100}
lst = list(counts.keys())
lst.sort()
for key in lst:
print(key, counts[key])
输出为
chuck 1
annie 42
jan 100
如果我想用字符串实现此效果,则字符串将表示为
"chuck 1\nannie 42\njan 100\n"
现在,如果我想完成这个字符串,我可以尝试类似:
for key, value in counts.items():
if value == 1:
counts[key] = "1\n"
elif value == 42:
counts[key] = "42\n"
elif value == 100:
counts[key] = "100\n"
temp = list(counts.items())
temp.sort()
myStr = str(temp)
for char in myStr:
if char in "[(',)]":
myStr = myStr.replace(char,'')
finalStr = "" + myStr[0:19] + "" + myStr[20:37] + "" + myStr[38:53] + ""
但是,是的,我认为我过于复杂的事情......什么是更好,更简单的方法?
谢谢!
答案 0 :(得分:2)
您可以通过将每个key, value
格式化为您期望的"{} {}".format(key, value)
然后,加入' \ n':
"\n".join(["{} {}".format(key, value) for key, value in counts.items()])
演示:
输入:
counts = {"chuck" : 1 , "annie" : 42, "jan" : 100}
输出:
jan 100
chuck 1
annie 42
注意到sorted
是必需的,所以这里有一个类别:
"\n".join(["{} {}".format(key, value) for key, value in sorted(counts.items())])
输出:
annie 42
chuck 1
jan 100
答案 1 :(得分:1)
简化排序:
>>> '\n'.join(sorted([k+' '+str(v) for k, v in counts.items())])
'annie 42\nchuck 1\njan 100'
对行进行排序而不是项目。按%timeit
衡量,这种方式实际上更快。
答案 2 :(得分:0)
它有点笨重:
'\n'.join(["{0} {1}".format(a,b) for a,b in counts.items()])
答案 3 :(得分:0)
如果你想要简明扼要。
d = {"chuck" : 1 , "annie" : 42, "jan" : 100}
'\n'.join('{} {}'.format(*item) for item in sorted(d.items()))
答案 4 :(得分:-1)
d = {"chuck" : 1 , "annie" : 42, "jan" : 100};
s = '\n'.join(['%s %s' % (key, value) for (key, value) in sorted(d.items(), key=lambda x: x[1])])
print(s) # 'chuck 1\nannie 42\njan 100'
d = {"chuck" : 1 , "annie" : 42, "jan" : 100};
s = '\n'.join(['%s %s' % (key, value) for (key, value) in sorted(d.items(), key=lambda x: x[0])])
print(s) # 'annie 42\nchuck 1\njan 100'