3 回答
TA贡献1831条经验 获得超10个赞
正如您要求布尔运算符
repeat=[1,4,5,6,7,8,9,9,1,5,7,7]
repeat = sorted(repeat)
for i in range(len(repeat)-1):
if repeat[i]==repeat[i+1]:
return True
return False
复杂度 O(nlog(n))
TA贡献1757条经验 获得超8个赞
def isDup(arrayList):
x={}
for i in arrayList:
if i in x:
return True
x[i]=1
return False
TA贡献1982条经验 获得超2个赞
显示是否存在重复项及其值(如果存在)的代码:
l = [1,4,5,6,7,8,9,9,1,5,7,7]
sl = sorted(l)
has_dups = any(f == s for f, s in zip(sl[:-1], sl[1:]))
dups_vals = sorted(set(f for f, s in zip(sl[:-1], sl[1:]) if f == s))
print('has dups:', has_dups, ', dups values:', dups_vals)
输出:
has dups: True , dups values: [1, 5, 7, 9]
代码工作缓慢,即一旦在排序数组中找到第一个重复项,它就会设置has_dups为(发现重复项)。True
如果输入数组非常大,则numpy可以使用它,这比纯 Python 快得多。接下来的代码使用以下代码实现相同的任务numpy(numpy需要安装一次python -m pip install numpy):
import numpy as np
l = [1,4,5,6,7,8,9,9,1,5,7,7]
sa = np.sort(l)
has_dups = np.any(sa[:-1] == sa[1:])
dups_vals = sa[np.append(np.diff(
np.insert((sa[:-1] == sa[1:]).astype(np.int8), 0, 0)
) == 1, False)]
print('has dups:', has_dups, ', dups values:', dups_vals)
输出相同:
has dups: True , dups values: [1 5 7 9]
还有另一个更简单的numpy解决方案:
import numpy as np
l = [1,4,5,6,7,8,9,9,1,5,7,7]
vals, cnts = np.unique(l, return_counts = True)
has_dups = np.any(cnts > 1)
dups_vals = vals[cnts > 1]
print('has dups:', has_dups, ', dups values:', dups_vals)
另外,只需检查是否有任何重复项可以使用简单的下一个代码来完成set():
l = [1,4,5,6,7,8,9,9,1,5,7,7]
has_dups = len(set(l)) < len(l)
print('has dups:', has_dups)
输出
has dups: True
添加回答
举报