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

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

How can I optimize this Python code to better performance?

问题

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

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

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

英文:

Is there any way to optimize this code?

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

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

答案1

得分: 1

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

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

  1. from collections import Counter
  2. def find_duplicates(lst):
  3. return [k for k, v in Counter(lst).items() if v > 1]
  4. print(find_duplicates([1,2,2,3,4,2,3]))

输出结果:

  1. [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

  1. from collections import Counter
  2. def find_duplicates(lst):
  3. return [k for k, v in Counter(lst).items() if v > 1]
  4. print(find_duplicates([1,2,2,3,4,2,3]))

Output:

  1. [2, 3]

答案2

得分: 0

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

  1. 这里有一个不使用导入库的想法
  2. def find_duplicates(lst):
  3. duped = set()
  4. return list(set(x for x in lst if x in duped or duped.add(x)))
  5. 请注意这里利用了add()返回None的事实
  6. 示例
  7. print(find_duplicates([1, 2, 3, 4, 3, 4, 6, 7, 3]))
  8. 输出
  9. [3, 4]
英文:

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

  1. def find_duplicates(lst):
  2. duped = set()
  3. 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:

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

gives

  1. [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:

确定