python找出数组重复_如何在Python中使用for循环查找数组中的重复元素?

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)

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.

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]

how do we use like this in Python?

for i in list_a:

for j in list_a[1:]:

....

I tried the above code. But it gets solution wrong. I don't know how to increase the value for j.

解决方案

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})

Unique List

>>> list(y)

[1, 2, 3, 5, 6, 7]

Items found more than 1 time

>>> [i for i in y if y[i]>1]

[2, 5]

Items found only one time

>>> [i for i in y if y[i]==1]

[1, 3, 6, 7]

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值