-4

I have the following list;

['html', 'header', 'title', 'body', 'div', 'div', 'div', 'div', 'div', 'ul', 'li', 'li', 'li']

i want to print items having occurrence three or more.

output should be 'li' and 'div'

Can anyone help me python code to do this.

Mazdak
  • 105,000
  • 18
  • 159
  • 188
Tarun Kumar
  • 729
  • 1
  • 8
  • 16
  • 1
    [`collections.Counter`](https://docs.python.org/2/library/collections.html#collections.Counter) – moooeeeep Jan 10 '15 at 12:30
  • wat u already tried? –  Jan 10 '15 at 12:30
  • Counting the occurance of an element is a duplicate of http://stackoverflow.com/questions/2600191/how-can-i-count-the-occurrences-of-a-list-item-in-python. The rest is basic logic. – Reti43 Jan 10 '15 at 12:30

4 Answers4

1

Try this:

>>> from collections import Counter

>>> l = ['html', 'header', 'title', 'body', 'div', 'div', 'div', 'div', 'div', 'ul', 'li', 'li', 'li']
>>> [item for item, cnt in Counter(l).items() if cnt > 2]
['li', 'div']
elyase
  • 39,479
  • 12
  • 112
  • 119
1

Without using Counter,

In [198]: e = ['html', 'header', 'title', 'body', 'div', 'div', 'div', 'div', 'div', 'ul', 'li', 'li', 'li']
In [199]: list(set([v for v in e if e.count(v)>=3]))
Out[199]: ['li', 'div']

(Only for short lists as it isn't too efficient).

xnx
  • 24,509
  • 11
  • 70
  • 109
0

Use collections module.

Counter method will add all items from list l as key and value is their counts. So you can find keys according their counts by your logic.

Code:

from collections import Counter

l = ['html', 'header', 'title', 'body', 'div', 'div', 'div', 'div', 'div', 'ul', 'li', 'li', 'li']

c = Counter(l)
for key, count in c.items():
    print("[{}] - {}".format(key, count))

Output:

[body] - 1
[ul] - 1
[title] - 1
[li] - 3
[header] - 1
[html] - 1
[div] - 5

Documentation for this module https://docs.python.org/2/library/collections.html

Vivek Sable
  • 9,938
  • 3
  • 40
  • 56
0
L = ['html', 'header', 'title', 'body', 'div', 'div', 'div', 'div', 'div', 'ul', 'li', 'li', 'li']

result = []

for i in range(len(L)):

    if L.count(L[i]) >= 3 and L[i] not in result:
        result.append(L[i])

print result

Output

['div', 'li']
Reti43
  • 9,656
  • 3
  • 28
  • 44
hariK
  • 2,722
  • 13
  • 18