2017-12-22 40 views
4

申し訳ありませんがトピックのタイトルは曖昧です、私は説明するのが難しいです。Pythonで辞書の値の重複を削除する

私は各値が項目のリストである辞書を持っています。私は重複した項目を削除したいので、各項目はリストに最小限の時間(一度は望ましい)表示されます。

辞書を考えてみましょう:

example_dictionary = {"weapon1":[1,2,3],"weapon2":[2,3],"weapon3":[2,3]} 

'weapon2' と 'weapon3' は同じ値を持っているので、それが生じるはずである:私は順序を気にしないので、

result_dictionary = {"weapon1":[1],"weapon2":[3],"weapon3":[2]} 

、それを

しかし、「選択肢がない」場合は値を残す必要があります。私はリラックスすることができます

result_dictionary = {"weapon1":[1],"weapon2":[3],"weapon3":[2],"weapon4":[3]} 

:それはキー空を離れることなく、一回のみのいずれか「2」または「3」に割り当てることができないので、可能な出力は次のようになり、今

example_dictionary = {"weapon1":[1,2,3],"weapon2":[2,3],"weapon3":[2,3],"weapon4":[3]} 

:この新しい辞書を考えてみましょう最初の部分だけに問題があり、管理しますが、私は2つの部分を一緒に解決する方が好きです。

+0

あなたは説明できます助けることができますか? weapon2とweapon3は最初のweapon1 [1,2,3]から値を取得しますか? –

+0

@AyodhyankitPaul weapon1は彼のリストに[1]を持っている唯一の人です。そのため[1]があります。 weapon2とweapon3はともに[2,3]なので、それぞれ個別の番号を取得します。そのうちの1つは[2]、もう1つは[3] –

答えて

1
#!/usr/bin/env python3 

example_dictionary = {"weapon1":[1,2,3],"weapon2":[2,3],"weapon3":[2,3]} 

result = {} 
used_values = [] 

def extract_semi_unique_value(my_list): 
    for val in my_list: 
     if val not in used_values: 
      used_values.append(val) 
      return val 
    return my_list[0] 

for key, value in example_dictionary.items(): 
    semi_unique_value = extract_semi_unique_value(value) 
    result[key] = [semi_unique_value] 

print(result) 
+1

'{'weaponA':[1、2 ]、[weaponB]:[1]} '。 – SCB

+0

全体の一意性は制約ではありませんでした。私が質問を正しく理解すれば、このケースでは[1]と[1]が許容されます。 –

+0

入力のサイズが大きくなる可能性があるので、できるだけ複雑にすることなく、[1]と[2] –

0

これはおそらく最も効率的な解決策ではありません。すべての可能な組み合わせに対する繰り返しが必要なため、大きなターゲットでは非常に遅く実行されます。

itertools.product()を使用して、可能な限りすべての組み合わせを取得します。次に、その中で最もユニークな数字の組み合わせを見つけることができます(セットの長さをテストすることによって)。例から

from itertools import product 
def dedup(weapons): 
    # get the keys and values ordered so we can join them back 
    # up again at the end 
    keys, vals = zip(*weapons.items()) 

    # because sets remove all duplicates, whichever combo has 
    # the longest set is the most unique 
    best = max(product(*vals), key=lambda combo: len(set(combo))) 

    # combine the keys and whatever we found was the best combo 
    return {k: [v] for k, v in zip(keys, best)} 

dedup({"weapon1":[1,2,3],"weapon2":[2,3],"weapon3":[2,3]}) 
#: {'weapon1': 1, 'weapon2': 2, 'weapon3': 3} 
dedup({"weapon1":[1,2,3],"weapon2":[2,3],"weapon3":[2,3],"weapon4":[3]}) 
#: {'weapon1': 1, 'weapon2': 2, 'weapon3': 2, 'weapon4': 3} 
0

これはweapon1が結果に[1]を持っている理由

import itertools 
res = {'weapon1': [1, 2, 3], 'weapon2': [2, 3], 'weapon3': [2, 3]} 
r = [[x] for x in list(set(list(itertools.chain.from_iterable(res.values()))))] 
r2 = [x for x in res.keys()] 
r3 = list(itertools.product(r2,r)) 
r4 = dict([r3[x] for x in range(0,len(r3)) if not x%4]) 
関連する問題