在 python 中将 3d 列表转换为 2d 列表

converting 3d lists to 2d lists in python

我有一个类似

的数组
sets=[ [ ['a', 'c'] , ['a', 'e'] ] , [ ['b', 'c'] , ['b', 'e'] ] , [ ['a','z'] ] ]

我想要减少列表的维度并删除内部列表中的公共元素

我的预期输出是

[['a','c','e'] , ['b','c','e'] , ['a','z'] ]
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
  1. 使用@cdleary 的解决方案将二维列表的列表展平:
  2. "Chunk" 使用@NedBatchelder 的解决方案生成的迭代器对象:

"Chunk"函数:

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

示例代码:

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']]