2017-08-13 102 views

回答

2

我想你需要轉換爲數組,然後再由ravel和最後轉換壓扁到list:由chain.from_iterable

a = [np.array([x]) for x in list('abcdefghij')] 
print (a) 
[array(['a'], 
     dtype='<U1'), array(['b'], 
     dtype='<U1'), array(['c'], 
     dtype='<U1'), array(['d'], 
     dtype='<U1'), array(['e'], 
     dtype='<U1'), array(['f'], 
     dtype='<U1'), array(['g'], 
     dtype='<U1'), array(['h'], 
     dtype='<U1'), array(['i'], 
     dtype='<U1'), array(['j'], 
     dtype='<U1')] 

b = np.array(a).ravel().tolist() 
print (b) 
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] 

與flattenting另一種解決方案:

from itertools import chain 

b = list(chain.from_iterable(a)) 
print (b) 
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] 
0

我發現,實現代碼我的請求: x = [str(i [0])for the_list]

+0

有必要轉換爲'str'? – jezrael

0

一個很好的普通p用'扁平'列表的內部數組(或對象dtype數組數組)的方式是使用concatenate函數之一。

例如用含有不同長度的陣列,包括一個0D)的列表:

In [600]: ll = [np.array('one'), np.array(['two','three']),np.array(['four'])] 
In [601]: ll 
Out[601]: 
[array('one', 
     dtype='<U3'), array(['two', 'three'], 
     dtype='<U5'), array(['four'], 
     dtype='<U4')] 
In [602]: np.hstack(ll).tolist() 
Out[602]: ['one', 'two', 'three', 'four'] 
In [603]: np.hstack(ll).tolist() 
Out[603]: ['one', 'two', 'three', 'four'] 

我不得不因爲我包括一個0D陣列使用hstack;如果他們都是1d concatenate就足夠了。


如果陣列都包含一個字符串,那麼其他的解決方案,做工精細

In [608]: ll = [np.array(['one']), np.array(['two']),np.array(['three']),np.array(['four'])] 
In [609]: ll 
Out[609]: 
[array(['one'], 
     dtype='<U3'), array(['two'], 
     dtype='<U3'), array(['three'], 
     dtype='<U5'), array(['four'], 
     dtype='<U4')] 

In [610]: np.hstack(ll).tolist() 
Out[610]: ['one', 'two', 'three', 'four'] 

In [611]: np.array(ll) 
Out[611]: 
array([['one'], 
     ['two'], 
     ['three'], 
     ['four']], 
     dtype='<U5') # a 2d array which can be raveled to 1d 

In [612]: [i[0] for i in ll]   # extracting the one element from each array 
Out[612]: ['one', 'two', 'three', 'four'] 
相關問題