如何将2d嵌套数组转换为2d数组单个?

时间:2019-03-07 08:39:56

标签: python-3.x

我有一个数组a,如下所示:[[(0,0),(2,0)],[(1,1)], [(3,8)]]

所以现在我要像这样转换它:[(0,0),(2,0),(1,1), (3,8)]

我该怎么办?

我尝试了下面的代码并获得了成功,但是我需要更好,更快的一些想法。

nresult = []
for i in range(len(result)):
    arr = result[i]
    for j in range(len(arr)):
        nresult.append(arr[j])

有人可以帮我吗?

谢谢!

3 个答案:

答案 0 :(得分:1)

您可以像这样从reduce中使用functools

from functools import reduce

a = [[(0,0),(2,0)],[(1,1)], [(3,8)]]
res = reduce(lambda x,y: x+y,a)

print(res) # [(0, 0), (2, 0), (1, 1), (3, 8)]

答案 1 :(得分:1)

如果可以确定嵌套的深度,则可以使用 itertools 包中的 chain

from itertools import chain

data = [[(0,0),(2,0)],[(1,1)], [(3,8)]]

result = list(chain(*data))

答案 2 :(得分:0)

您可以使用列表推导-

$(document).ready(function() {
  var div_clone = null;
  div_clone = $('.template').clone();
  $('.button-add').click(function() {
    //we select the box clone it and insert it after the box
    var _elm = div_clone.clone();
    _elm.find('.box-title').html('Other Address');
    _elm.find("input[type='text']").val("");
    _elm.find('.remove_btn').show();
    _elm.appendTo('#clone_here');
  })

  $(document).on("click", ".remove_btn", function(e) {
    var $e = $(e.currentTarget);
    $e.closest('.template').remove();
  });
});