Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print elements in a list in new lines?

I have a list

L = Counter(mywords)

Where

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'] 

It's much longer than that but that's a snippet.

Now what I do next is:

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

Because I want it to show the 10 most commonly used words in that list AND their counts, but I want it to print out into new lines for each item in the list, instead I get this error:

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

Any help would be appreciated, using Python 3.

like image 689
Goose Avatar asked Feb 19 '23 18:02

Goose


2 Answers

print ("\n".join(map(str, c.most_common(10))))

If you want more control over the format, you can use a format string like this

print ("\n".join("{}: {}".format(k,v) for k,v in c.most_common(10)))
like image 196
John La Rooy Avatar answered Feb 27 '23 09:02

John La Rooy


The simplest is:

for item, freq in L.most_common(10):
    print(item, 'has a count of', freq) # or
    print('there are {} occurrences of "{}"'.format(freq, item))
like image 42
Jon Clements Avatar answered Feb 27 '23 11:02

Jon Clements