問題描述
我有一個 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 列表中獲取唯一的元組,無論順序如何的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!