如何优化这段Python代码以提高性能?

huangapple go评论66阅读模式
英文:

How can I optimize this Python code to better performance?

问题

有没有办法优化这段代码?

def find_duplicates(lst):
    duplicates = []
    for i in range(len(lst)):
        for j in range(i + 1, len(lst)):
            if lst[i] == lst[j] and lst[i] not in duplicates:
                duplicates.append(lst[i])
    return duplicates

上面的代码已经是对另一段代码的改进,但我认为它可以进一步优化。

英文:

Is there any way to optimize this code?

def find_duplicates(lst):
    duplicates = []
    for i in range(len(lst)):
        for j in range(i + 1, len(lst)):
            if lst[i] == lst[j] and lst[i] not in duplicates:
                duplicates.append(lst[i])
    return duplicates

The code above is already an improvement of another code, but I think it can be improved

答案1

得分: 1

你可以使用 collection.Counter 类,然后迭代其内容来实现你的目标。

以下代码识别出在列表中出现多次的项 - 也就是不一定是重复项

from collections import Counter

def find_duplicates(lst):
    return [k for k, v in Counter(lst).items() if v > 1]

print(find_duplicates([1,2,2,3,4,2,3]))

输出结果:

[2, 3]
英文:

You can utilise the collection.Counter class then iterate over its contents to achieve your objective.

The following code identifies items that appear more than once in the list - i.e., not necessarily duplicates

from collections import Counter

def find_duplicates(lst):
    return [k for k, v in Counter(lst).items() if v > 1]

print(find_duplicates([1,2,2,3,4,2,3]))

Output:

[2, 3]

答案2

得分: 0

以下是翻译好的代码部分:

这里有一个不使用导入库的想法

def find_duplicates(lst):
    duped = set()
    return list(set(x for x in lst if x in duped or duped.add(x))) 

请注意这里利用了add()返回None的事实

示例

print(find_duplicates([1, 2, 3, 4, 3, 4, 6, 7, 3]))

输出

[3, 4]
英文:

Here's one idea which does not use an imported library:

def find_duplicates(lst):
    duped = set()
    return list(set(x for x in lst if x in duped or duped.add(x))) 

Note this uses the fact that add() returns None

Example:

print(find_duplicates([1, 2, 3, 4, 3, 4, 6, 7, 3]))

gives

[3, 4]

huangapple
  • 本文由 发表于 2023年5月17日 21:53:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76272899.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定