4

この問題について正しく考えているかどうかはわかりません。重複のあるリストを取得し、反復サフィックスを追加してリストを「重複除去」する関数を書きたいと思います。

例えば:

dup_list = ['apple','banana','cherry','banana','cherry','orange','cherry']

復帰を目指して:

deduped = ['apple','banana1','cherry1','banana2','cherry2','orange','cherry3']

私の本能は、次のように、while ステートメントでリストを反復処理しながら pop 関数を使用することでした。

def dedup_suffix(an_list):
dedup=[]
for each in an_list:
    an_list.pop(an_list.index(each)) #pop it out
    i=1 #iterator  
    while each in an_list:
        an_list.pop(an_list.index(each))
        i+=1
        appendage=str(each)+"_"+str(i)
    else:
        appendage=str(each)
    dedup.append(appendage)
return dedup

しかし:

>>> dedup_suffix(dup_list)

['リンゴ'、'チェリー'、'オレンジ']

ポインタに感謝します。

4

2 に答える 2

4

Counterを使用して、発生回数を追跡できます。apple最初の出現にゼロを追加したくないように、あなたの例は に関して正しいと仮定しています。そのためには、少しのロジックが必要です。

from collections import Counter
counter = Counter()

dup_list = ['apple','banana','cherry','banana','cherry','orange','cherry']
deduped = []
for name in dup_list:
    new = name + str(counter[name]) if counter[name] else name
    counter.update({name: 1})
    deduped.append(new)
于 2013-06-24T20:17:42.863 に答える
1

collections.Counter オブジェクトを使用して、重複の数をカウントできます。次に、それを繰り返して新しいリストを作成します

dup_list = ['apple','banana','cherry','banana','cherry','orange','cherry']
c = Counter(dup_list)

dedup=[]
for w in c:
    n = c[w]
    if n == 1:
        dedup.append(w)
    else:
        for i in range(1,n+1):
            dedup.append(w+str(i))
于 2013-06-24T20:24:21.863 に答える