2017-06-13 124 views
3

我有这样需要的输出

[[{1:"one",2:"two"},{1:"one"}],[{3:"three",4:"four"},{3:"three"}]] 

所需的输出列表:

[{1:"one",2:"two"},{1:"one"},{3:"three",4:"four"},{3:"three"}] 

有人能告诉我如何进行?

+0

这就是所谓扁平化的列表。请参阅https://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python,https://stackoverflow.com/questions/406121/flattening-a -shallow一览中-蟒?noredirect = 1&LQ = 1。一个好的答案是'[子列表中项目的L子项列表]' – Stuart

回答

1

迭代列表的列表以将其添加到另一个列表。

list_1 = [[{1:"one",2:"two"},{1:"one"}],[{3:"three",4:"four"},{3:"three"}]] 
list_2 = [] 
for list in list_1: 
    for dictionary in list: 
     list_2.append(dictionary) 

print(list_2) # [{1: 'one', 2: 'two'}, {1: 'one'}, {3: 'three', 4: 'four'}, {3: 'three'}] 
+0

不!得到这个作为输出: [{u'1':u'one',u'2':u'two'},{u'1':u'one'}] –

+0

@ArohiGupta我的错误;我编辑了答案,再试一次。 –

+0

任何想法如何从输出中删除“unicode”? –

0

你可以试试这个:

from itertools import chain 

l = [[{1:"one",2:"two"},{1:"one"}],[{3:"three",4:"four"},{3:"three"}]] 

new_l = list(chain(*l)) 

最终输出:

[{1: 'one', 2: 'two'}, {1: 'one'}, {3: 'three', 4: 'four'}, {3: 'three'}]