如何在Python中使用for循环查找数组中的重复元素? [英] How to find duplicate elements in array using for loop in Python?

查看:206
本文介绍了如何在Python中使用for循环查找数组中的重复元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

tmp = []

在list_a中为
如果tmp .__包含__(i):
打印i
else:
tmp.append(i)

我已经用上面的代码找到 list_a 中的重复元素。我不想从列表中删除元素。



但是我想在这里使用for循环。
通常C / C ++我们使用这样我猜:

  for(int i = 0; i <= list_a (int j = i + 1; j< = list_a.length; j ++)
if(list_a [i] == list_a [j])
print list_a [i]

我们在Python中如何使用?


$在list_a中的

 :list_a [1:]中的

....

我尝试了上面的代码。但它会解决错误。我不知道如何增加 j 的价值。

解决方案

仅供参考,在python 2.7+中,我们可以使用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
计数器({2:2,5:2,1:1,3:1,6:1,7:1})

唯一列表

 >>>列表(y)
[1,2,3,5,6,7]

发现超过1次的项目

 >>> [i for y in y if y [i]> 1] 
[2,5]

仅发现一次的项目

 >>> [i for y in y if y [i] == 1] 
[1,3,6,7]


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]

这篇关于如何在Python中使用for循环查找数组中的重复元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆