之前做1月總結的時候說過希望每天或者每2天開始的更新一些學習筆記,這是開始的第一篇。
這篇介紹的是如何把一個 itertools.chain 對象轉換為一個數組。
參考 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 itertoolschain = itertools.chain(*list_of_numbers)
解決方法有兩種:
第一種比較簡單,直接采用 list 方法,如下所示:
list(chain)
但缺點有兩個:
會在外層多嵌套一個列表
效率并不高
第二個就是利用 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])
對比兩種方法的運算時間,如下所示:
>>> 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 方法的運算速度會更快。
補充:下面看下itertools 的 chain() 方法
# -*- coding:utf-8 -*-from itertools import chainfrom random import randint# 隨機生成 19 個整數(在 60 到 100 之間)c1 = [randint(60, 100) for _ in range(19)]# 隨機生成 24 個整數(在 60 到 100 之間)c2 = [randint(60, 100) for _ in range(24)]# 隨機生成 42 個整數(在 60 到 100 之間)c3 = [randint(60, 100) for _ in range(42)]# 隨機生成 22 個整數(在 60 到 100 之間)c4 = [randint(60, 100) for _ in range(22)]count = 0# chain()可以把一組迭代對象串聯起來,形成一個更大的迭代器for s in chain(c1, c2, c3, c4): if s > 90: count += 1print('4 個班單科成績大于 90 分的人次為', count)
總結
以上所述是小編給大家介紹的Python轉換itertools.chain對象為數組的方法,希望對大家有所幫助!
新聞熱點
疑難解答