Saran
Saran

Reputation: 179

converting 3d lists to 2d lists in python

I have an array like

sets=[ [ ['a', 'c'] , ['a', 'e'] ] , [ ['b', 'c'] , ['b', 'e'] ] , [ ['a','z'] ] ]

I wanted the reduced dimension of list and remove common element in the innerlists

My expected output is

[['a','c','e'] , ['b','c','e'] , ['a','z'] ]

Upvotes: 1

Views: 1432

Answers (2)

Saran
Saran

Reputation: 179

sets1=[[['a', 'c'], ['a', 'e']], [ ['b', 'c'] , ['b', 'e']] ,[['a','z']] ]

a=[] 

for i in xrange(len(sets1)):
    b=[]
    for j in xrange(len(sets1[i])):
        for k in xrange(len(sets1[i][j])):
            if(sets1[i][j][k] not in b ):
                b.append(sets1[i][j][k])
    a.append(b)
print a

Upvotes: 1

mechanical_meat
mechanical_meat

Reputation: 169334

  1. Flatten your list of lists of 2d lists using @cdleary's solution: https://stackoverflow.com/a/406199/42346
  2. "Chunk" the resultant iterator object using @NedBatchelder's solution: https://stackoverflow.com/a/312464/42346

"Chunk" function:

def chunks(l, n):
    """ Yield successive n-sized chunks from l. """
    for i in xrange(0, len(l), n):
        yield l[i:i+n]

Example code:

import itertools as it
l = list(it.chain(*it.chain(*sets)))
print(list(chunks(l,3)))
# -> [['a', 'c', 'a'], ['e', 'b', 'c'], ['b', 'e', 'a'], ['z']]

Upvotes: 0

Related Questions