3 回答

TA貢獻1831條經(jīng)驗 獲得超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條經(jīng)驗 獲得超8個贊
def isDup(arrayList):
x={}
for i in arrayList:
if i in x:
return True
x[i]=1
return False

TA貢獻1982條經(jīng)驗 獲得超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]
代碼工作緩慢,即一旦在排序數(shù)組中找到第一個重復項,它就會設(shè)置has_dups為(發(fā)現(xiàn)重復項)。True
如果輸入數(shù)組非常大,則numpy可以使用它,這比純 Python 快得多。接下來的代碼使用以下代碼實現(xiàn)相同的任務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
添加回答
舉報