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

查看:67
本文介绍了如何在 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)

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

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 循环.通常我们使用的 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]

我们如何在 Python 中这样使用?

how do we use like this in Python?

for i in list_a:
    for j in list_a[1:]:
    ....

我尝试了上面的代码.但它得到了错误的解决方案.我不知道如何增加 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]

找到超过 1 次的项目

Items found more than 1 time

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

仅找到一次的项目

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

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

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