在 python 列表中获取唯一的元组,无论顺序如何 [英] Grab unique tuples in python list, irrespective of order

查看:14
本文介绍了在 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 列表中获取唯一的元组,无论顺序如何的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆