how to extract nested lists?
本问题已经有最佳答案,请猛点这里访问。
Duplicates:
- Flattening a shallow list in Python
- Comprehension for flattening a sequence of sequences?
假设我有一个包含嵌套列表的列表:
1 | [["a","b","c"], ["d","e","f"], ["g","h","i","j"]...] |
把它转换成这样一个列表的最好方法是什么
1 | ["a","b","c","d","e"....] |
使用
1 2 3 | from itertools import chain list(chain.from_iterable(list_of_lists)) |
在
1 2 3 | >>> from itertools import chain >>> list(chain(*x)) ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] |
或者,它可以很容易地在一个单一的列表理解中完成:
1 2 3 | >>> x=[["a","b","c"], ["d","e","f"], ["g","h","i","j"]] >>> [j for i in x for j in i] ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] |
或通过
1 2 3 | >>> from operator import add >>> reduce(add, x) ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] |
使用
1 2 3 4 5 6 7 | >>> li = [["a","b","c"], ["d","e","f"], ["g","h","i","j"]] >>> chained = [] >>> while li: ... chained.extend(li.pop(0)) ... >>> chained ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] |
编辑:上面的示例将在构建新列表时使用原始列表,因此,如果您操作非常大的列表并希望将内存使用率降至最低,那么这将是一个优势。如果不是这样的话,我会考虑使用更多的Python疗法来达到这个结果。