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 列表中获取唯一的元组,无论顺序如何
基础教程推荐
- 症状类型错误:无法确定关系的真值 2022-01-01
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01
- Python 的 List 是如何实现的? 2022-01-01
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01
- 如何在Python中绘制多元函数? 2022-01-01
- 合并具有多索引的两个数据帧 2022-01-01
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01
- 哪些 Python 包提供独立的事件系统? 2022-01-01
- 使用Python匹配Stata加权xtil命令的确定方法? 2022-01-01
- 将 YAML 文件转换为 python dict 2022-01-01