問(wèn)題描述
我有一個(gè)包含重復(fù)元素的列表:
I have a list with duplicate elements:
list_a=[1,2,3,5,6,7,5,2]
tmp=[]
for i in list_a:
if tmp.__contains__(i):
print i
else:
tmp.append(i)
我已經(jīng)使用上面的代碼在 list_a
中找到了重復(fù)的元素.我不想從列表中刪除元素.
I have used the above code to find the duplicate elements in the list_a
. I don't want to remove the elements from list.
但我想在這里使用 for 循環(huán).通常我們使用的 C/C++ 我猜是這樣的:
But I want to use for loop here. Normally C/C++ we use like this I guess:
for (int i=0;i<=list_a.length;i++)
for (int j=i+1;j<=list_a.length;j++)
if (list_a[i]==list_a[j])
print list_a[i]
我們?nèi)绾卧?Python 中這樣使用?
how do we use like this in Python?
for i in list_a:
for j in list_a[1:]:
....
我嘗試了上面的代碼.但它得到了錯(cuò)誤的解決方案.我不知道如何增加 j
的值.
I tried the above code. But it gets solution wrong. I don't know how to increase the value for j
.
推薦答案
僅供參考,在python 2.7+,我們可以使用Counter
Just for information, In python 2.7+, we can use Counter
import collections
x=[1, 2, 3, 5, 6, 7, 5, 2]
>>> x
[1, 2, 3, 5, 6, 7, 5, 2]
>>> y=collections.Counter(x)
>>> y
Counter({2: 2, 5: 2, 1: 1, 3: 1, 6: 1, 7: 1})
唯一列表
>>> list(y)
[1, 2, 3, 5, 6, 7]
找到超過(guò) 1 次的項(xiàng)目
Items found more than 1 time
>>> [i for i in y if y[i]>1]
[2, 5]
僅找到一次的項(xiàng)目
>>> [i for i in y if y[i]==1]
[1, 3, 6, 7]
這篇關(guān)于如何在 Python 中使用 for 循環(huán)查找數(shù)組中的重復(fù)元素?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!