脚本专栏 
首页 > 脚本专栏 > 浏览文章

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

(编辑:jimmy 日期: 2024/5/20 浏览:3 次 )

之前做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对象为数组的方法,希望对大家有所帮助!

上一篇:如何解决tensorflow恢复模型的特定值时出错
下一篇:python range实例用法分享
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网