Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a unique list of items that occur more than once in a list

I have a list of items:

mylist = ['A','A','B','C','D','E','D']

I want to return a unique list of items that appear more than once in mylist, so that my desired output would be:

 [A,D]

Not sure how to even being this, but my though process is to first append a count of each item, then remove anything equal to 1. Then dedupe, but this seems like a really roundabout, inefficient way to do it, so I am looking for advice.

like image 753
user2242044 Avatar asked Nov 06 '14 06:11

user2242044


People also ask

How do I get a list of unique lists in python?

Using Python's import numpy, the unique elements in the array are also obtained. In the first step convert the list to x=numpy. array(list) and then use numpy. unique(x) function to get the unique values from the list.

How do you find the frequency of unique values in a list?

You can use the combination of the SUM and COUNTIF functions to count unique values in Excel. The syntax for this combined formula is = SUM(IF(1/COUNTIF(data, data)=1,1,0)). Here the COUNTIF formula counts the number of times each value in the range appears.

How do you check if a value appears more than once in a list python?

count() method to check if a value occurs multiple times in a list, e.g. if my_list. count(my_str) > 1: . The list. count() method will return an integer greater than 1 if the value occurs multiple times in the list.

How do you find all occurrences of a number in a list?

One of the most basic ways to get the index positions of all occurrences of an element in a Python list is by using a for loop and the Python enumerate function. The enumerate function is used to iterate over an object and returns both the index and element.


2 Answers

You can use collections.Counter to do what you have described easily:

from collections import Counter
mylist = ['A','A','B','C','D','E','D']
cnt = Counter(mylist)
print [k for k, v in cnt.iteritems() if v > 1]
# ['A', 'D']
like image 147
YS-L Avatar answered Nov 12 '22 01:11

YS-L


>>> mylist = ['A','A','B','C','D','E','D']
>>> set([i for i in mylist if mylist.count(i)>1])
set(['A', 'D'])
like image 30
Irshad Bhat Avatar answered Nov 12 '22 01:11

Irshad Bhat