例如:
newList = [1, 1, 2, 2, 2, 2, 3, 4, 4, 4, 4, 5, 5]
我需要的列表是:
newList = [3]
另一个例子:
tempList = [["cheese", "ham"], ["spinach", "dressing"], ["cheese", "ham"]]
列表将是:
tempList = [["spinach", "dressing"]]
它不能使用任何对不可散列的项目不起作用的东西——真正的列表将存储在其中的列表。我还将拥有超过 100,000 个对象,因此速度是最重要的因素。我不需要列表按任何顺序排列。
这是我到目前为止的想法:
newList.sort()
i = 0
while i < newList.__len__()-1:
x = 1
while newList[i].__eq__(newList[i + x]):
x += 1
if not (i + x <= newList.__len__()- 1):
break
if x != 1:
for j in range(i, i + x):
del newList[i]
i-=1
i+=1
这可行,但我想知道是否有更有效的方法。
请您参考如下方法:
我建议生成一个新列表。一个简单的循环就可以了:
lst = [1, 1, 2, 2, 2, 2, 3, 4, 4, 4, 4, 5, 5]
new = []
for x in lst:
if lst.count(x) == 1:
new.append(x)
print(new)
#output:
[3]
