使用解压缩连接嵌套列表

时间:2019-04-08 00:42:18

标签: python

我有这样一个嵌套数组

In [12]: print(f"{arr}")                                                                 
[[0, 1, 2], [7, 8, 9, 10], [12, 13, 14, 15, 16, 17]]

我要串联内部的三个数组

arr = [[0, 1, 2], [7, 8, 9, 10], [12, 13, 14, 15, 16, 17]]
res, k = [], 0
for i in range(len(arr)): 
    for j in range(len(arr[i])): 
        res.append(arr[i][j])

In [26]: [arr[i][j] for i in range(len(arr)) for j in range(len(arr[i]))]                                 
Out[26]: [0, 1, 2, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17]

如何使用拆包来解决问题

In [27]: [*a for a in arr]                                                                                
  File "<ipython-input-27-4ab599207747>", line 1
    [*a for a in arr]
    ^
SyntaxError: iterable unpacking cannot be used in comprehension

0 个答案:

没有答案