简体   繁体   中英

Easy way to find what item repeated in list

So I have list like

 l = [1,2,3,4,4]

If I make a set obvilously I will get

([1,2,3,4])

I need a way to find what item repeated in list and was popped out and I do not want to use looping. If there is an easy way to do so? I'm using python 2.7

You'll have to iterate the list, explicitly or implicitly. One way using standard libraries would be with collections.Counter :

In [1]: from collections import Counter

In [2]: l = [1,2,3,4,4]

In [3]: Counter(l).most_common(1)[0][0]
Out[3]: 4

A Counter object is a dictionary with elements of some iterable as keys and their respective counts as values:

In [4]: Counter(l)
Out[4]: Counter({4: 2, 1: 1, 2: 1, 3: 1})

Its most_common() method returns a list of items with highest counts:

In [5]: Counter(l).most_common()
Out[5]: [(4, 2), (1, 1), (2, 1), (3, 1)]

The optional argument restricts the length of the returned list:

In [6]: Counter(l).most_common(1)
Out[6]: [(4, 2)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM