Home  >  Q&A  >  body text

python2.x如何列表推导二维数组?

>>> a = [[1, 2, 3], [4, 5, 6]]
>>> b = [x for x in i for i in a]
>>> b
[1, 1, 2, 2, 3, 3]
>>> c = [x for x in i for i in a] 
>>> c
[4, 4, 5, 5, 6, 6]
  1. 如何解释上面代码的运行结果?
    一般的得到的结果是[4, 4, 5, 5, 6, 6],但是偶然会得到[1, 1, 2, 2, 3, 3],这是为什么呢?

  2. 如何把[[1, 2, 3], [4, 5, 6]]用列表推导成[1,2,3,4,5,6]的形式?

伊谢尔伦伊谢尔伦2718 days ago873

reply all(3)I'll reply

  • 迷茫

    迷茫2017-04-17 15:16:04

    b = [x for x in i for i in a] does not work in my interpreter.

    How to deduce [[1, 2, 3], [4, 5, 6]] into the form [1,2,3,4,5,6] using a list?

    >>> b = [item for sublist in a for item in sublist]
    >>> b
    [1, 2, 3, 4, 5, 6]
    

    flatten There is a detailed discussion on stack overflow. The above method is found to be the fastest,

    reply
    0
  • 高洛峰

    高洛峰2017-04-17 15:16:04

    a = [[1, 2, 3], [4, 5, 6]]
    all = []
    for i in a:
        all += i
    

    I didn’t think of a simpler way.

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-17 15:16:04

    In [5]: b = [x for i in a for x in i]

    In [6]: b
    Out[6]: [1, 2, 3, 4, 5, 6]

    三维的
    In [7]: aa = [[[1], [2], [3]], [[4], [5], [6]]]
    In [8]: b = [y for i in aa for x in i for y in x]

    In [9]: b
    Out[9]: [1, 2, 3, 4, 5, 6]

    reply
    0
  • Cancelreply