【问题标题】:removing copies from a list [duplicate]从列表中删除副本[重复]
【发布时间】:2018-11-06 20:50:48
【问题描述】:

对于上下文:用户可以将项目添加到列表中。我想删除所有相同的提交。有没有更有效的方法来做到这一点:?

def removeCopies(self):
    i = 0
    while i != self.size:
        number = self.contents.count(self.contents[i])
        if number != 1:
            for j in range(1, number):
                self.delete(self.contents.index(self.contents[i], i + 1))
        i += 1

【问题讨论】:

标签: python


【解决方案1】:

我能想到的最有效的删除重复项的方法是

self.contents = list(set(self.contents))

这不会保留您项目的顺序,但至少您不会以 O(n3) 算法结束。

更好的解决方案是将self.contents 设为set 开头,这样如果您可以选择这样做,用户根本无法输入重复项。

【讨论】:

    猜你喜欢
    • 2021-03-08
    • 2019-04-18
    • 2016-02-15
    • 2014-09-30
    • 1970-01-01
    • 2011-01-13
    • 2012-07-11
    相关资源
    最近更新 更多