Merging sublists in python
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
Flattening a shallow list in Python
Making a flat list out of list of lists in Python
Merge two lists in python?
快速简单的问题:
如何合并此项。
1 | [['a','b','c'],['d','e','f']] |
对此:
1 | ['a','b','c','d','e','f'] |
使用列表理解:
1 2 | ar = [['a','b','c'],['d','e','f']] concat_list = [j for i in ar for j in i] |
列表连接只是用
所以
1 2 3 4 5 | total = [] for i in [['a','b','c'],['d','e','f']]: total += i print total |
这样做:
1 2 | a = [['a','b','c'],['d','e','f']] reduce(lambda x,y:x+y,a) |
尝试:
1 | sum([['a','b','c'], ['d','e','f']], []) |
或更长但更快:
1 | [i for l in [['a', 'b', 'c'], ['d', 'e', 'f']] for i in l] |
或者按照ashwinichaudhary的建议使用
1 | list(itertools.chain(*[['a', 'b', 'c'], ['d', 'e', 'f']])) |
尝试列表对象的"扩展"方法:
1 2 3 4 5 | >>> res = [] >>> for list_to_extend in range(0, 10), range(10, 20): res.extend(list_to_extend) >>> res [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] |
或更短:
1 2 3 4 | >>> res = [] >>> map(res.extend, ([1, 2, 3], [4, 5, 6])) >>> res [1, 2, 3, 4, 5, 6] |
1 | mergedlist = list_letters[0] + list_letters[1] |
这假设您有一个静态长度的列表,并且您总是希望合并前两个
1 2 3 | >>> list_letters=[['a','b'],['c','d']] >>> list_letters[0]+list_letters[1] ['a', 'b', 'c', 'd'] |