【发布时间】:2019-09-13 01:44:10
【问题描述】:
我有一个包含等长序列的列表(在这个例子中,序列的长度是 2,但它可以比其他情况下更长)的数字,例如:
[[3, 2], [0, 6], [6, 0], [7, 7], [0, 5], [7, 7]]
现在我要删除所有重复项([7, 7] 出现两次),但还要删除所有反向重复项([0, 6] 和 [6, 0])。
我当前的代码是这样的:
def getUniqueShapes(shapes):
unique = []
for shape in shapes:
if shape not in unique and reversed(shape) not in unique:
shapes.append(shape)
print(unique)
我对这个例子的预期输出是
[[3, 2], [0, 6], [7, 7], [0, 5]]
因为not in,这个算法运行速度很差。
有没有一种简单的方法可以将这种条件应用到具有更好时间复杂度的列表中?
【问题讨论】:
-
你考虑过使用集合吗?
-
你也不要在这段代码中追加到唯一
-
{1, 2} == {2, 1}... -
你的样本输出是什么?
-
我的意思是你的预期结果