3 回答

TA貢獻(xiàn)1946條經(jīng)驗(yàn) 獲得超4個(gè)贊
您的代碼將所有重復(fù)值附加到新列表,即“a”。要僅保留 1 個(gè)重復(fù)值,您需要檢查列表中是否已經(jīng)存在相同的值。如果這不存在,那么只有您應(yīng)該將該值附加到您的列表中。我已經(jīng)修改了您的代碼,以適應(yīng)這種需要。
enter code here
some_list=['a','b','c','b','d','m','n','n']
a=[]
for items in some_list:
if some_list.count(items) > 1 and a.count(items) == 0:
a.append(items)
print (a)
輸出:
['b', 'n']

TA貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超9個(gè)贊
some_list=['a','b','c','b','d','m','n','n']
a=[]
for items in some_list:
if some_list.count(items) > 1:
if items not in a:
a.append(items)
print (a)
輸出:
['b', 'n']
或者:
some_list=['a','b','c','b','d','m','n','n']
a=[]
for items in some_list:
if some_list.count(items) > 1:
a.append(items)
a=set(a)
print (a)
出去:
['b', 'n']

TA貢獻(xiàn)2003條經(jīng)驗(yàn) 獲得超2個(gè)贊
如果您在if語句中再添加一個(gè)條件,您的代碼將起作用。
some_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n']
a = []
for items in some_list:
if some_list.count(items) > 1 and items not in a:
a.append(items)
print (a)
輸出:-
['b', 'n']
添加回答
舉報(bào)