有些時候我們會需要將一個有很多層的list解開,變成一維的list。其實三行程式碼就可以解決這個問題。只要你懂得如何使用reduce這個工具。
[][1]
#!/usr/bin/env python
import collections
flatten = lambda p, c : p+reduce(flatten,c,[]) if isinstance(c, collections.Iterable) else p+[c,]
nested_list = [1, 2, 3, 4, 5, 6, [7, 8, [9, 10], [11, [12], 13]], 14, [15, 16, [17, [18, [19, 20], 21], 22, 23], 24, 25]]
print flatten([], nested_list)
輸出結果如下:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21,
22, 23, 24, 25]
[1]: