过滤列表python重复的项目

时间:2012-12-27 05:11:13

标签: python list filter

  

可能重复:
  Find and list duplicates in Python list

我在Python中有这个脚本:

routes = Trayect.objects.extra(where=['point_id IN (10,59)'])

for route in routes:
    print route

我收到了这个回复:

6 的 106 114 的 110 118 158 210 的 110 102 105 的 110 120 195 的 106

正如您所说,“110”路线重复3次,“106”重复2次。

如何才能获得重复的数字?

我只想 110 106 ,而不是其他人。就是这样:

106 110

我不是英语母语人士,我正在学习python。感谢

***列表中的对象是字符串

3 个答案:

答案 0 :(得分:1)

这可能是最简单的方法,即使routes中有很多项目也很有效:

from collections import Counter

counts = Counter(routes)

multi_routes = [i for i in counts if counts[i] > 1]

示例用法(使用数字,但这适用于可散列类型,例如字符串很好):

>>> from collections import Counter
>>> c = Counter([1,1,2,3,3,4,5,5,5])
>>> [i for i in c if c[i] > 1]
[1, 3, 5]

答案 1 :(得分:0)

你需要这样的东西吗?

In [1]: s = "6 106 114 110 118 158 210 110 102 105 110 120 195 106"

In [2]: l = s.split()

In [3]: [x for x in l if l.count(x) > 1]
Out[3]: ['106', '110', '110', '110', '106']

In [4]: set([x for x in l if l.count(x) > 1])
Out[4]: set(['106', '110'])

答案 2 :(得分:0)

routes = [i for i in set(routes) if routes.count(i) > 1]
相关问题