1

重複の可能性:
Python リストで重複を検索して一覧表示する

私は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 回繰り返されます。

繰り返し数だけを取得するにはどうすればよいですか?

110106のみが必要で、他は必要ありません。これだけ:

106 110

私は英語のネイティブ スピーカーではなく、python を学んでいます。ありがとう

***リスト内のオブジェクトは文字列です

4

3 に答える 3

2

This is probably the most straightforward way to do it, and also efficient even if routes has many items in it:

from collections import Counter

counts = Counter(routes)

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

Example usage (using numbers, but this will work for hashable type, e.g. strings are fine):

>>> 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]
于 2012-12-27T05:19:41.453 に答える
0
routes = [i for i in set(routes) if routes.count(i) > 1]
于 2012-12-27T05:17:00.560 に答える
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'])
于 2012-12-27T05:16:00.293 に答える