问题描述
我已经使用itertools
生成了一个组合列表,并且得到的结果看起来像这样:
I've generated a list of combinations, using itertools
and I'm getting a result that looks like this:
nums = [-5,5,4,-3,0,0,4,-2]
x = [x for x in set(itertools.combinations(nums, 4)) if sum(x)==target]
>>> x = [(-5, 5, 0, 4), (-5, 5, 4, 0), (5, 4, -3, -2), (5, -3, 4, -2)]
删除无序重复项(例如x[0]
和x[1]
)的最有效的时间复杂度方法是重复项.有内置的东西可以处理吗?
What is the most time-complexity wise efficient way of removing unordered duplicates, such as x[0]
and x[1]
are the duplicates. Is there anything built in to handle this?
我的一般方法是在一个元素中创建所有元素的计数器,然后与下一个元素进行比较.这是最好的方法吗?
My general approach would be to create a counter of all elements in one and compare to the next. Would this be the best approach?
谢谢您的指导.
推荐答案
由于要查找无序重复项,最好的方法是通过类型转换. Typecast 作为 set
.由于set仅包含 不可变 元素.因此,我制作了一组 tuples
.
Since you want to find unordered duplicates the best way to go is by typecasting. Typecast them as set
. Since set only contains immutable elements. So, I made a set of tuples
.
>>> set(map(tuple,map(sorted,x)))
{(-3, -2, 4, 5), (-5, 0, 4, 5)}
这篇关于在2D数组中删除无序重复项的最省时方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!