2017-12-22 7 views
4

죄송합니다. 주제가 막연합니다. 설명하기가 어렵습니다.파이썬에서 사전의 중복 값 제거

각 값이 항목 목록 인 사전이 있습니다. 중복 된 항목을 제거하여 각 항목이 목록에 최소 횟수 (한 번이라도 바람직 함)로 표시되도록하고 싶습니다.

은 사전 고려 :

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

'weapon2'와 'weapon3'같은 값을 가진다을, 그래서 그것을가 발생할한다 : 나는 순서를 신경 쓰지 않기 때문에

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

, 그것을 또한 결과는 다음과 같습니다.

그러나 "선택의 여지가 없습니다"는 경우 값을 남겨 두어야합니다. 이 새 사전 고려 : 그것은 키 빈을 떠나지 않고 한 번만 '3'중 '2'를 지정하거나 할 수 없기 때문에, 지금

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

을, 가능한 출력은 다음과 같습니다

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

내가 휴식을 취할 수 있습니다 나는이 아마 가장 효율적인 해결책이 아니라 함께

+0

당신이 설명 할 수 도움이 될 수 [1] 결과에? weapon2와 weapon3은 첫 번째 무기 1 [1,2,3]에서 값을 가져 옵니까? –

+0

@AyodhyankitPaul weapon1은 그의 목록에 [1]이있는 유일한 사람입니다. 그 이유는 [1]입니다. weapon2와 weapon3 모두 [2,3]이므로 개별 숫자를 얻습니다. 그 중 하나는 [2]가되고 다른 하나는 [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

이 무기 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])