欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

Python转换itertools.chain对象为数组的方法

时间:2021-05-03 09:59:10|栏目:Python代码|点击:

之前做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实战之实现excel读取、统计、写入的示例讲解

栏    目:Python代码

下一篇:Python使用paramiko操作linux的方法讲解

本文标题:Python转换itertools.chain对象为数组的方法

本文地址:http://www.codeinn.net/misctech/113495.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有