例如,给定列表['one', 'two', 'one'],算法应该返回True,而给定['one', 'two', 'three']则应该返回False。
当前回答
def check_duplicates(my_list):
seen = {}
for item in my_list:
if seen.get(item):
return True
seen[item] = True
return False
其他回答
另一种简洁的方法是使用Counter。
要确定原始列表中是否有重复项:
from collections import Counter
def has_dupes(l):
# second element of the tuple has number of repetitions
return Counter(l).most_common()[0][1] > 1
或者获取重复项的列表:
def get_dupes(l):
return [k for k, v in Counter(l).items() if v > 1]
my_list = ['one', 'two', 'one']
duplicates = []
for value in my_list:
if my_list.count(value) > 1:
if value not in duplicates:
duplicates.append(value)
print(duplicates) //["one"]
仅推荐用于短列表:
any(thelist.count(x) > 1 for x in thelist)
不要在一个很长的列表上使用——它所花费的时间与列表中项目数量的平方成正比!
对于具有可哈希项(字符串,数字和c)的较长列表:
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平方),没有人能做什么:-(。
def check_duplicates(my_list):
seen = {}
for item in my_list:
if seen.get(item):
return True
seen[item] = True
return False
如果所有值都是可哈希的,使用set()删除重复项:
>>> your_list = ['one', 'two', 'one']
>>> len(your_list) != len(set(your_list))
True
推荐文章
- 如何在PHP中截断字符串最接近于一定数量的字符?
- 试图在Windows 10上运行Python时出现“权限被拒绝”
- 如何在Django中设置时区
- 即使模板文件存在,Flask也会引发TemplateNotFound错误
- defaultdict的嵌套defaultdict
- 构造tkinter应用程序的最佳方法?
- 如何在Python中逐行打印字典?
- 当试图运行Python脚本时,“ImportError:没有命名模块”
- pylab和pyplot的区别是什么?
- 如何分裂()一个分隔字符串到一个列表<字符串>
- Argparse:确定使用了哪个子解析器
- django导入错误-没有core.management模块
- 在芹菜中检索队列中的任务列表
- c#对象列表,我如何得到一个属性的和
- Ruby数组到字符串的转换