1

I had a list like:

l = [[(3,4)], [(3,7)], [(3,8)]]

I used the chain() function to flat the list, now I have a list like:

l2 = [3,4,3,7,3,8]

I want to separate the duplicate items into another list:

l3 = [3,3,3]
l4 = [4,7,8]

I used the set() function, but it destroyed the duplicate items and resulted in:

l3 = [4,7,8]

but I want to obtain both of them separately

1
  • Does the order of items have to be preserved? Commented Mar 1, 2013 at 10:20

2 Answers 2

7

You'd have to do some kind of count. Using the collections.Counter() class would make that easy:

from collections import Counter
counts = Counter(main_list)

duplicate_list, unique_list = [], []
for entry in main_list:
    if counts[entry] > 1:
        duplicate_list.append(entry)
    else:
        unique_list.append(entry)

counts is a multi-set or bag; a mapping of entry to it's count in main_list. The above example preserves the ordering of main_list.

3
  • I changed the variable names as l2 looks like 12 in the font. Also, descriptive variable names are always a Good Thing. Commented Mar 5, 2013 at 8:27
  • @BurhanKhalid: Thanks; note that I was following the OP names there, making it easier to test out the solution. Commented Mar 5, 2013 at 9:45
  • Yes I know, I don't know why people use single letter names, really. Commented Mar 5, 2013 at 9:48
0

extention to @Martijn Pieters answer, you can use ifilter to filter out those that match the criteria in the lambda expression(first argument in ifilter):

from collections import Counter
from itertools import ifilter

counts = Counter(l2)    

l3 = list(ifilter(lambda x: counts[x] > 1, l2))
l4 = list(ifilter(lambda x: counts[x] == 1, l2))
0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.