Python转换itertools.chain对象为数组的方法
之前做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 itertools chain = 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 chain
from 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 += 1
print('4 个班单科成绩大于 90 分的人次为', count)
总结
以上所述是小编给大家介绍的Python转换itertools.chain对象为数组的方法,希望对大家有所帮助!
相关文章
使用Python & Flask 实现RESTful Web API的实例
下面小编就为大家带来一篇使用Python & Flask 实现RESTful Web API的实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧2017-09-09
Python面向对象程序设计类变量与成员变量、类方法与成员方法用法分析
这篇文章主要介绍了Python面向对象程序设计类变量与成员变量、类方法与成员方法用法,结合实例形式较为详细的分析了类变量与成员变量、类方法与成员方法、类方法与静态方法等概念、原理及使用技巧,需要的朋友可以参考下2019-04-04
Pytorch中使用ImageFolder读取数据集时忽略特定文件
这篇文章主要介绍了Pytorch中使用ImageFolder读取数据集时忽略特定文件,具有一的参考价值需要的小伙伴可以参考一下,希望对你有所帮助2022-03-03


最新评论