python - 在计算列表项时查找重复
问题描述
我需要知道在计算所述列表时是否存在用于在整数列表中查找第一个重复子集的算法。例如,给定一个函数,它以这样的 for 元素输出
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]
推荐阅读
- react-native - 在 Expo 上保存大数据以供离线使用
- python - python发送udp数据包 - 并不总是发送
- sonarqube - 在 Cake Frosting 上的 Cake.Sonar 中出现错误
- ios - 如何在 OS X swift 中关闭前一个视图控制器时从一个 NS 视图控制器移动到另一个?
- python - cv2.COLOR_BGR2HSV 的色调输出与计算值不对应
- javascript - 使用 Rollup 构建自定义 npm 包中的 react-select 崩溃
- antlr - ANTLR4 NEWLINE 在每个表达式,但对于最后一个可选
- java - 使用 Apache LDAP API 在下次登录 Active Directory 时强制更改密码
- typescript - Typescript 通用抽象类 - 为什么这个抽象方法不继承类类型?
- copy - 比较 2 行,如果值相同,则复制单元格