英文:
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]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论