首页 > 解决方案 > 在计算列表项时查找重复

问题描述

我需要知道在计算所述列表时是否存在用于在整数列表中查找第一个重复子集的算法。例如,给定一个函数,它以这样的 for 元素输出

1
2
3
1
2
3

我希望能够在第一次出现重复时中断,只留下

[1,2,3]

原因是出于性能原因我不想计算整个列表。有什么办法吗?谢谢!

标签: pythonperformance

解决方案


我为您编写了一个示例代码:

代码:

nums = [1, 2, 3, 1, 2, 3]
result = []
for num in nums:
    if num in result:
        break  # Break the iteration if the element already exists in the result list
    result.append(num)

print("Result: {}".format(result))

输出:

>>> python3 test.py 
Result: [1, 2, 3]

推荐阅读