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

时间:2015-04-20 17:26:52

标签: python python-2.7 subset nested-lists

我有一个像

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

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

我的预期输出是

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

2 个答案:

答案 0 :(得分:1)

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 :(得分:0)

  1. 使用@ cdleary的解决方案展平您的二维列表列表:https://stackoverflow.com/a/406199/42346
  2. "大块"使用@ NedBatchelder解决方案生成的迭代器对象:https://stackoverflow.com/a/312464/42346
  3. "大块"功能:

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