我有一个包含重复元素的列表:
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 循环查找数组中的重复元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
如何在python中的感兴趣区域周围绘制一个矩形How to draw a rectangle around a region of interest in python(如何在python中的感兴趣区域周围绘制一个矩形)
如何使用 OpenCV 检测和跟踪人员?How can I detect and track people using OpenCV?(如何使用 OpenCV 检测和跟踪人员?)
如何在图像的多个矩形边界框中应用阈值?How to apply threshold within multiple rectangular bounding boxes in an image?(如何在图像的多个矩形边界框中应用阈值?)
如何下载 Coco Dataset 的特定部分?How can I download a specific part of Coco Dataset?(如何下载 Coco Dataset 的特定部分?)
根据文本方向检测图像方向角度Detect image orientation angle based on text direction(根据文本方向检测图像方向角度)
使用 Opencv 检测图像中矩形的中心和角度Detect centre and angle of rectangles in an image using Opencv(使用 Opencv 检测图像中矩形的中心和角度)