0

I am trying to tie two different things together. 1. Find and print unique items in a list. 2. Pass a int value and print unique items in the first n items

I have two things that work, but not in conjunction, to split the list into sub-lists of n:

def find_uniques(3):

lista = ['a', 'a', 'b','c','d','c','e','d','e','f','f']

lists = [lista[x:x+n] for x in xrange(0, len(lista), n)]

print lists

[['a', 'a', 'b'], ['c', 'd', 'c'], ['e', 'd', 'e'], ['f', 'f']]

# 2nd part works on the whole list

print [a for a in lista if lista.count(a) == 1]

['b']

# How do I get the second part to work on the sub lists, and give me back unique chars from each sub list.

The output I am looking for: [['b'],['d'], ['d']]

1 Answers1

0

Usually it is easier to just split out these operations instead of merging, but here is a nested list comprehension.

lista = ['a', 'a', 'b','c','d','c','e','d','e','f','f']
n = 3
[[ item for item in sublist if sublist.count(item) == 1] for sublist in [ lista[x:x+n] for x in xrange(0, len(lista), n) ] ]

Personally, although it is longer, I prefer a more readable version like so:

def findunique(lista,n=3):
    listoflists = [ lista[x:x+n] for x in xrange(0,len(lista),n) ]
    results = []
    for sublist in listoflists:
        unique = [ item for item in sublist if sublist.count(item) == 1]
        if unique:
            results.append(unique)
    return results

lista = ['a','a','b','c','d','c','e','d','e','f','f']    
print findunique(lista,3)
beroe
  • 11,784
  • 5
  • 34
  • 79
  • Really appreciate the answer, it is hard to read for a beginner like me, you mentioned it was easier to spit out the operations? How would you go about that, make some new lists, then apply the count on the separate lists? Could you give an example please? – user6348278 Oct 12 '16 at 01:18