Grab unique tuples in python list, irrespective of order(在 python 列表中获取唯一的元组,无论顺序如何)
问题描述
我有一个 python 列表:
[(2,2),(2,3),(1,4),(2,2) 等...]我需要的是某种功能,将其简化为独特的组件...在上面的列表中:
[ (2,2),(2,3),(1,4) ]<小时>
numpy unique 并没有完全做到这一点.我可以想到一种方法——将我的元组转换为数字,[22,23,14,etc.],找到唯一的,然后从那里开始工作......但我没有不知道复杂性是否会失控.有没有一个函数可以做我想要对元组做的事情?
下面是演示问题的代码示例:
将 numpy 导入为 npx = [(2,2),(2,2),(2,3)]y = np.unique(x)<块引用>
返回:y: [2 3]
这里是演示修复的解决方案的实现:
x = [(2,2),(2,2),(2,3)]y = 列表(集合(x))<块引用>
返回 y: [(2,2),(2,3)]
你可以这样做
y = np.unique(x, axis=0)z = []对于 y 中的 i:z.append(元组(i))原因是 numpy 将元组列表解释为二维数组.通过设置axis = 0,您会要求numpy不要展平数组并返回唯一的行.
I have a python list:
[ (2,2),(2,3),(1,4),(2,2), etc...]
What I need is some kind of function that reduces it to its unique components... which would be, in the above list:
[ (2,2),(2,3),(1,4) ]
numpy unique does not quite do this. I can think of a way to do it--convert my tuples to numbers, [22,23,14,etc.], find the uniques, and work back from there...but I don't know if the complexity won't get out of hand. Is there a function that will do what I am trying to do with tuples?
Here is a sample of code that demonstrates the problem:
import numpy as np
x = [(2,2),(2,2),(2,3)]
y = np.unique(x)
returns: y: [2 3]
And here is the implementation of the solution that demonstrates the fix:
x = [(2,2),(2,2),(2,3)]
y = list(set(x))
returns y: [(2,2),(2,3)]
you could simply do
y = np.unique(x, axis=0)
z = []
for i in y:
z.append(tuple(i))
The reason is that a list of tuples is interpreted by numpy as a 2D array. By setting axis=0, you'd be asking numpy not to flatten the array and return unique rows.
这篇关于在 python 列表中获取唯一的元组,无论顺序如何的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 python 列表中获取唯一的元组,无论顺序如何
基础教程推荐
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
