计算列表项时发现重复



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

1
2
3
1
2
3

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

[1,2,3]

原因是出于性能原因,我不想计算整个列表。有办法吗?非常感谢。

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

代码:

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]

@milanbalaz解决方案的替代方案,它不会停止在单个重复元素上,而是停止在重复序列上:

nums = [1,2,3,1,1,2,3,1]
result = []
for i, num in enumerate(nums):
if result and result == nums[i:i+len(result)]:
print(f'Found repetition: {result}')
# Break the iteration when the sequence in result is the same
# as the upcoming sequence in nums
break 
result.append(num)
print(f'Result: {result}')

输出

Found repetition: [1, 2, 3, 1]
Result: [1, 2, 3, 1]

最新更新