Constructing a Python set from a Numpy matrix(从 Numpy 矩阵构造 Python 集)
问题描述
我正在尝试执行以下操作
I'm trying to execute the following
>> from numpy import *
>> x = array([[3,2,3],[4,4,4]])
>> y = set(x)
TypeError: unhashable type: 'numpy.ndarray'
如何轻松高效地创建包含 Numpy 数组中所有元素的集合?
How can I easily and efficiently create a set with all the elements from the Numpy array?
推荐答案
如果你想要一组元素,这里有另一种可能更快的方法:
If you want a set of the elements, here is another, probably faster way:
y = set(x.flatten())
PS:在x.flat、x.flatten()和x.ravel()之间进行比较后 在 10x100 阵列上,我发现它们都以大致相同的速度执行.对于 3x3 数组,最快的版本是迭代器版本:
PS: after performing comparisons between x.flat, x.flatten(), and x.ravel() on a 10x100 array, I found out that they all perform at about the same speed. For a 3x3 array, the fastest version is the iterator version:
y = set(x.flat)
我会推荐它,因为它是内存成本较低的版本(它可以很好地随着数组的大小而扩展).
which I would recommend because it is the less memory expensive version (it scales up well with the size of the array).
PPS:还有一个 NumPy 函数可以做类似的事情:
PPS: There is also a NumPy function that does something similar:
y = numpy.unique(x)
这确实会生成一个与 set(x.flat) 具有相同元素的 NumPy 数组,但它是一个 NumPy 数组.这非常快(几乎快 10 倍),但是如果你需要一个 set,那么执行 set(numpy.unique(x)) 会比另一个慢一点程序(构建一个集合需要很大的开销).
This does produce a NumPy array with the same element as set(x.flat), but as a NumPy array. This is very fast (almost 10 times faster), but if you need a set, then doing set(numpy.unique(x)) is a bit slower than the other procedures (building a set comes with a large overhead).
这篇关于从 Numpy 矩阵构造 Python 集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 Numpy 矩阵构造 Python 集
基础教程推荐
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
