如何检查列表中是否有重复的数字

repeat=[1,4,5,6,7,8,9,9,1,5,7,7]

如何使用 python 的布尔运算符检查是否有 2 个或更多重复项。这是我的代码


repeat = set()

for x in one_sample:

    if x in repeat: 

        return True

    repeat.add(x)

return False

print(repeat)


慕姐4208626
浏览 108回答 3
3回答

慕哥6287543

正如您要求布尔运算符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 Truereturn False复杂度 O(nlog(n))

陪伴而非守候

def isDup(arrayList):     x={}  for i in arrayList:    if i in x:      return True    x[i]=1  return False

临摹微笑

显示是否存在重复项及其值(如果存在)的代码:在线尝试一下!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 npl = [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(&nbsp; &nbsp; 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 npl = [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
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python