[英]Convert a list of 1x1 dimensional arrays to list of floats in python
我有以下形式的清單:
[array([ 3755.16235032]),
array([ 3755.16235032]),
array([ 3755.16235032]),
array([ 3755.16235032])]
我想要一份表格清單:
[3755.16235032,
3755.16235032,
3755.16235032,
3755.16235032]
第一個列表的每個元素都是一個sci kit學習回歸器的結果。 我想要第二種格式,以便繪制分類器的預測。
使用np.concatenate
避免手動迭代:
my_list = [np.array([ 3755.16235032]),
np.array([ 3755.16235032]),
np.array([ 3755.16235032]),
np.array([ 3755.16235032])]
new_list = np.concatenate(my_list).tolist()
>>> new_list
[3755.16235032, 3755.16235032, 3755.16235032, 3755.16235032]
根據評論中的廣泛討論,這是我的基准測試:
my_list = [np.random.randn(1) for _ in range(100000)]
def concat_method(my_list=my_list):
return np.concatenate(my_list).tolist()
def hstack_method(my_list=my_list):
return np.hstack(my_list).tolist()
def flatten_method(my_list=my_list):
return np.array(my_list).flatten().tolist()
def ravel_method(my_list=my_list):
return np.array(my_list).ravel().tolist()
import timeit
>>> timeit.timeit(concat_method, number=100) / 100
0.025655772869977226
>>> timeit.timeit(hstack_method, number=100) / 100
0.1172302443100125
>>> timeit.timeit(ravel_method, number=100) / 100
0.041237239889997
>>> timeit.timeit(flatten_method, number=100) / 100
0.0412076849100049
另一個解決方案:給定x
是您的輸入list
,您可以使用NumPy中的ravel()
作為
xlst = list(np.array(x).ravel())
print (xlst)
或者您可以使用flatten()
作為
xlst = list(np.array(x).flatten())
print (xlst)
如果您只想將最終答案作為數組,則無需將list
放在=
之后。 並且,如果您的輸入x
已經是numpy數組類型,請將np.array(x).ravel()
替換為x.ravel()
。
或者,如上面的答案中已經提到的,也可以使用np.array(x).flatten().tolist()
和np.array(x).ravel().tolist()
代替使用list()
轉換為列表np.array(x).flatten().tolist()
np.array(x).ravel().tolist()
出於以下一種答案中的注釋(感謝評論者)的啟發,對本頁列出的所有可能答案進行了一些時間分析(由於格式問題,很容易將其放在此處而不是注釋中):
x = np.array([np.array([i]) for i in range(100000)])
%timeit np.concatenate(x).tolist()
%timeit np.hstack(x).tolist()
%timeit x.flatten().tolist()
%timeit x.ravel().tolist()
輸出量
10 loops, best of 3: 55.2 ms per loop
10 loops, best of 3: 155 ms per loop
100 loops, best of 3: 2.45 ms per loop
100 loops, best of 3: 2.29 ms per loop
通過使用hstack
np.hstack(my_list).tolist()
Out[180]: [3755.16235032, 3755.16235032, 3755.16235032, 3755.16235032]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.