2014-05-12 06:19

题目链接

原题:

Given an input list of lists.. flatten the list. For e.g. 

{{1,2}, {3}, {4,5}} ... Output should be {1, 2, 3, 4, 5}

题目:给定一个二维数组,把它展开成一维数组。

解法:之前做了一道题,把维度不定的数组展开成一维数组。这题也能用那题的代码来解决。

代码:

 1 # http://www.careercup.com/question?id=5485521224597504
 2 #!/usr/bin/python
 3 
 4 def flatten(container, new_container):
 5     for element in container:
 6         if isinstance(element, list) or isinstance(element, tuple) or isinstance(element, set):
 7             flatten(element, new_container)
 8         else:
 9             new_container.append(element)
10     pass
11     
12 if __name__ == '__main__':
13     a = [1, 2.3, [3, [1, 222]], (4, 111, 0), "string", set([1, "hello", 3.33])]
14     res = []
15     flatten(a, res)
16     print(res)
17     pass
18     

 

 posted on 2014-05-12 06:27  zhuli19901106  阅读(263)  评论(0编辑  收藏  举报