您好,登錄后才能下訂單哦!
之前做1月總結(jié)的時候說過希望每天或者每2天開始的更新一些學(xué)習(xí)筆記,這是開始的第一篇。
這篇介紹的是如何把一個 itertools.chain 對象轉(zhuǎn)換為一個數(shù)組。
參考 stackoverflow 上的一個回答:Get an array back from an itertools.chain object,鏈接如下:
https://stackoverflow.com/questions/26853860/get-an-array-back-from-an-itertools-chain-object
例子:
list_of_numbers = [[1, 2], [3], []] import itertools chain = itertools.chain(*list_of_numbers)
解決方法有兩種:
第一種比較簡單,直接采用 list 方法,如下所示:
list(chain)
但缺點(diǎn)有兩個:
會在外層多嵌套一個列表
效率并不高
第二個就是利用 numpy 庫的方法 np.fromiter ,示例如下:
>>> import numpy as np >>> from itertools import chain >>> list_of_numbers = [[1, 2], [3], []] >>> np.fromiter(chain(*list_of_numbers), dtype=int) array([1, 2, 3])
對比兩種方法的運(yùn)算時間,如下所示:
>>> list_of_numbers = [[1, 2]*1000, [3]*1000, []]*1000 >>> %timeit np.fromiter(chain(*list_of_numbers), dtype=int) 10 loops, best of 3: 103 ms per loop >>> %timeit np.array(list(chain(*list_of_numbers))) 1 loops, best of 3: 199 ms per loop
可以看到采用 numpy 方法的運(yùn)算速度會更快。
補(bǔ)充:下面看下itertools 的 chain() 方法
# -*- coding:utf-8 -*- from itertools import chain from random import randint # 隨機(jī)生成 19 個整數(shù)(在 60 到 100 之間) c1 = [randint(60, 100) for _ in range(19)] # 隨機(jī)生成 24 個整數(shù)(在 60 到 100 之間) c2 = [randint(60, 100) for _ in range(24)] # 隨機(jī)生成 42 個整數(shù)(在 60 到 100 之間) c3 = [randint(60, 100) for _ in range(42)] # 隨機(jī)生成 22 個整數(shù)(在 60 到 100 之間) c4 = [randint(60, 100) for _ in range(22)] count = 0 # chain()可以把一組迭代對象串聯(lián)起來,形成一個更大的迭代器 for s in chain(c1, c2, c3, c4): if s > 90: count += 1 print('4 個班單科成績大于 90 分的人次為', count)
總結(jié)
以上所述是小編給大家介紹的Python轉(zhuǎn)換itertools.chain對象為數(shù)組的方法,希望對大家有所幫助!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。