For example, given the list ['one', 'two', 'one']
, the algorithm should return True
, whereas given ['one', 'two', 'three']
it should return False
.
原文由 teggy 发布,翻译遵循 CC BY-SA 4.0 许可协议
For example, given the list ['one', 'two', 'one']
, the algorithm should return True
, whereas given ['one', 'two', 'three']
it should return False
.
原文由 teggy 发布,翻译遵循 CC BY-SA 4.0 许可协议
仅推荐用于 短 列表:
any(thelist.count(x) > 1 for x in thelist)
不要 在长列表上使用——它花费的时间可能与列表中项目数的 平方 成正比!
对于带有可哈希项(字符串、数字等)的较长列表:
def anydup(thelist):
seen = set()
for x in thelist:
if x in seen: return True
seen.add(x)
return False
如果您的项目不可散列(子列表、字典等),它会变得更毛茸茸,但如果它们至少具有可比性,仍然有可能获得 O(N logN)。但是您需要知道或测试项目的特征(可散列与否,可比较与否)以获得最佳性能 - 可散列为 O(N),不可散列可比较为 O(N log N),否则它下降到 O(N 平方) 并且对此无能为力:-(。
原文由 Alex Martelli 发布,翻译遵循 CC BY-SA 2.5 许可协议
2 回答5.1k 阅读✓ 已解决
2 回答1.1k 阅读✓ 已解决
4 回答1k 阅读✓ 已解决
3 回答1.1k 阅读✓ 已解决
3 回答1.2k 阅读✓ 已解决
1 回答2.8k 阅读✓ 已解决
1 回答1.7k 阅读✓ 已解决
如果所有值都是可哈希的,请使用 ---
set()
删除重复项: