-1
country=['Uruguay', 'Mexico', 'Uruguay', 'France', 'Mexico']

I have to count the occurrence of element in list. This is my output.

['Uruguay', 2, 'Mexico', 2, 'France', 1]

But how to do the list in list like below?

[['Uruguay', 2], ['Mexico', 2], ['France', 1]]
ray8693
  • 1
  • 1

2 Answers2

0

You can implement with list comprehension.

In [5]: print [[i,country.count(i)] for i in set(country)]
Out[5]: [['Mexico', 2], ['France', 1], ['Uruguay', 2]]

Also with collections.Counter,

from collections import Counter
result = map(list,Counter(country).items())
Rahul K P
  • 15,740
  • 4
  • 35
  • 52
0

Take a look at collections.Counter and List Comprehensions

>>> country = ['Uruguay', 'Mexico', 'Uruguay', 'France', 'Mexico']
>>> [[i, j] for i, j in collections.Counter(country).items()]
[['Mexico', 2], ['France', 1], ['Uruguay', 2]]
luoluo
  • 5,353
  • 3
  • 30
  • 41