面試題(5)
阿新 • • 發佈:2019-01-02
如何把巢狀的python list轉成一個一維的python list?
a = [[1,2,3], [5, 2, 8], [7,8,9]], 想把a變成[1,2,3, 5, 2, 8, 7,8,9]
1 最簡單的
a = [[1,2,3],[4,5,6], [7], [8,9]]
a= sum=(a,[])
2 python3
from functools import reduce
a = [[1,2,3],[4,5,6], [7], [8,9]]
a= reduce(lambda x,y:x+y,a)
3 自知乎大神的暴力黑科技
a = [[1,2,3],[4,5,6], [7], [8,9]]
a = eval('[%s]'%repr(a).replace('[', '').replace(']', ''))
4 itertools.chain.from_iterable()方法
import itertools
a = [[1,2,3],[4,5,6], [7], [8,9]]
a = list(itertools.chain.from_iterable(a))
5 使用numpy中flatten()
注:該函式只能適用於numpy物件,即array或者mat,普通的list列表是不行的。
from numpy import *
a = [[1,2,3], [5, 2, 8], [7,8,9]]
a =array(a)
a = list(a.flatten())
Out: [1, 2, 3, 5, 2, 8, 7, 8, 9]
等等還有其他大神的一些方法就不一一列舉了,有興趣的可以點選知乎連結
檢視更多方法哦