如何以新行打印列表中的元素?

2024-05-18 21:41:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一张单子

L = Counter(mywords)

其中

mywords = ['Well', 'Jim', 'opportunity', 'I', 'Governor', 'University', 'Denver', 'hospitality', 'There', 'lot', 'points', 'I', 'make', 'tonight', 'important', '20', 'years', 'ago', 'I', 'luckiest', 'man', 'earth', 'Michelle', 'agreed', 'marry', '(Laughter)', 'And', 'I', 'Sweetie', 'happy'] 

它比那要长得多,但那只是一个片段。

现在我接下来要做的是:

print ("\n".join(c.most_common(10)))

因为我想让它显示列表中10个最常用的单词及其计数,但是我想让它为列表中的每一项打印成新行,而我得到的是这个错误:

TypeError: sequence item 0: expected str instance, tuple found

使用Python 3,任何帮助都将不胜感激。


Tags: 列表makecounterpoints单子lottherewell
3条回答
print ("\n".join(map(str, c.most_common(10))))

如果您想要对格式进行更多控制,可以使用如下格式字符串

print ("\n".join("{}: {}".format(k,v) for k,v in c.most_common(10)))

如果你只想要这些字符串:

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返回的序列的每个成员执行某些操作。python的方法是使用列表理解或生成器表达式。

同时,你应该学会如何调试这些类型的案例。当join给你一个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)))

最简单的是:

for item, freq in L.most_common(10):
    print(item, 'has a count of', freq) # or
    print('there are {} occurrences of "{}"'.format(freq, item))

相关问题 更多 >

    热门问题