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

查看:73
本文介绍了不论顺序如何,都可以在python列表中获取唯一的元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个python列表:

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并不能完全做到这一点.我可以想到一种方法-将元组转换为数字,[22,23,14,etc.],找到唯一性,然后从那里开始工作...但是我不知道复杂性是否会一发不可收拾.是否有可以执行我要使用元组的功能?


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)

返回:y:[2 3]

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))

返回y:[(2,2),(2,3)]

returns y: [(2,2),(2,3)]

推荐答案

您可以轻松完成

y = np.unique(x, axis=0)
z = [] 
for i in y:
   z.append(tuple(i))

原因是numpy将元组列表解释为2D数组.通过设置axis = 0,您将要求numpy不要展平数组并返回唯一的行.

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天全站免登陆