我正在努力解决问题表格中的印刷问题。到目前为止,我已设法按字母顺序排序用户输入的句子并计算每个单词出现的次数。这是代码:
thestring = (raw_input())
sentence = thestring.split(" ")
sentence.sort()
count = {}
for word in thestring.split():
try: count[word] += 1
except KeyError: count[word] = 1
print sentence
print count
当我运行代码时,我得到了这个:
['apple', 'apple', 'banana', 'mango', 'orange', 'pear', 'pear', 'strawberry']
{'apple': 2, 'pear': 2, 'strawberry': 1, 'mango': 1, 'orange': 1, 'banana': 1}
但是,理想情况下,我希望将其打印在类似于:
的表格中apple.....|.....2
banana....|.....1
mango.....|.....1
orange....|.....1
pear......|.....2
strawberry|.....1
感谢您的帮助!
答案 0 :(得分:5)
format
是打印格式化字符串的pythonic方式:
d = {'apple': 2, 'pear': 2, 'strawberry': 1, 'mango': 1, 'orange': 1, 'banana': 1}
for word, count in sorted(d.items()):
print "{:20} | {:5}".format(word, count)
自动调整第一列的大小:
maxlen = max(map(len, d))
for word, count in sorted(d.items()):
print "{:{}} | {}".format(word, maxlen, count)
如果你真的想用点(或其他)填充它,那么就像这样:
for word, count in sorted(d.items()):
print "{:.<{}}|{:.>5}".format(word, maxlen, count)
apple.....|....2 banana....|....1 mango.....|....1 orange....|....1 pear......|....2 strawberry|....1
正如已经指出的那样,对于第一部分,最好使用Counter
。
答案 1 :(得分:3)
sentence = thestring.split(" ")
from collections import Counter
for fruit, num in sorted(Counter(sentence).items()):
print "{:10}|{:5}".format(fruit.ljust(10, "."), str(num).rjust(5, "."))
<强>输出强>
apple.....|....2
banana....|....1
mango.....|....1
orange....|....1
pear......|....2
strawberry|....1
您可以使用format examples了解其工作原理。
答案 2 :(得分:2)
您应该使用collections.Counter
:
from collections import Counter
thestring = (raw_input()).split(" ")
cnt = Counter(thestring)
items = cnt.items()
items.sort(key=lambda x: x[0])
print items
答案 3 :(得分:0)
Counter
是更好的解决方案,但如果您想坚持使用代码,只需将print count
替换为
for c in sorted(count):
print c + '.'*(10-len(c))+'|'+'.'*(6-len(str(count[c])))+str(count[c])
答案 4 :(得分:0)
d = {'apple': 2, 'pear': 2, 'strawberry': 1, 'mango': 1, 'orange': 1, 'banana': 1}
for v,k in d.items():
s = str(v).ljust(l, '.') + "|" + str(k).rjust(10, '.')
print s
其中l是你最长的钥匙。
在输出上你有:
apple.....|.........2
pear......|.........2
strawberry|.........1
mango.....|.........1
orange....|.........1
banana....|.........1