如果你只想要字符串:
print("\n".join(element for element, count in c.most_common(10)))
如果您希望以以下形式打印字符串和计数('foo', 11)
:
print ("\n".join(str(element_and_count)
for element_and_count in c.most_common(10)))
如果您想要您选择的其他格式的字符串和计数:
print ("\n".join("{}: {}".format(element, count)
for element, count in c.most_common(10)))
为什么?该most_common
函数返回(element, count)
对。这些东西是元组,而不是字符串。你不能只是将元组连接在一起。当然,您可以将其转换为字符串(上面的选项 #2),但这仅在您确实需要('foo', 11)
每行的格式时才有效。要获得其他两个选项,您想忽略一半的元组并使用另一个,或者编写自己的格式表达式。
在任何情况下,您都希望对返回的序列的每个成员执行一些操作most_common
。Pythonic 的方法是使用列表推导或生成器表达式。
同时,您应该学习如何调试这些情况。什么时候join
给你 a TypeError
,把它分解成几块,直到你找到一个可以存储的东西(并用 2 而不是 10 尝试它,这样可以减少阅读量):
>>> print("\n".join(c.most_common(2)))
TypeError: sequence item 0: expected str instance, tuple found
>>> c.most_common(2)
[('I', 4), ('man', 1)]
啊哈!列表中的每个事物都是两个事物的元组,而不仅仅是一个字符串。为什么?
>>> help(c.most_common)
most_common(self, n=None) method of collections.Counter instance
List the n most common elements and their counts from the most
common to the least. If n is None, then list all element counts.
>>> Counter('abcdeabcdabcaba').most_common(3)
[('a', 5), ('b', 4), ('c', 3)]
好的,所以它返回最常见的元素及其计数。我只想要元素。所以:
>>> [element for element, count in c.most_common(2)]
['I', 'man']
现在我可以加入:
>>> '\n'.join([element for element, count in c.most_common(2)])
'I\nman'
而且我不需要括号和父母(我可以只使用表达式而不是列表理解):
>>> '\n'.join(element for element, count in c.most_common(2))
'I\nman'
现在,我可以打印它了:
>>> print('\n'.join(element for element, count in c.most_common(2)))
I
man
现在它正在工作,打印所有 10 个:
>>> print('\n'.join(element for element, count in c.most_common(10)))